Python文件处理如何操作?这里有详细的例子————

本文概述

到目前为止, 我们一直在从控制台获取输入, 并将其写回到控制台以与用户进行交互。

有时仅在控制台上显示数据是不够的。要显示的数据可能非常大, 并且只能在控制台上显示有限数量的数据, 并且由于内存是易失性的, 因此无法一次又一次地恢复以编程方式生成的数据。

但是, 如果需要这样做, 我们可以将其存储在易失性的本地文件系统中, 并且每次都可以访问。在这里, 需要文件处理。

在本教程的这一部分中, 我们将学习有关python中文件处理的所有信息, 包括创建文件, 打开文件, 关闭文件, 编写和附加文件等。

打开文件

Python提供了open()函数, 该函数接受两个参数, 即文件名和访问文件的访问方式。该函数返回一个文件对象, 该文件对象可用于执行各种操作, 例如读取, 写入等。

下面给出了使用open()函数的语法。

file object = open(<file-name>, <access-mode>, <buffering>)

可以使用各种模式(如读, 写或追加)访问文件。以下是有关打开文件的访问模式的详细信息。

SN 存取方式 Description
1 r 它将文件打开为只读。文件指针位于开头。如果未通过任何访问模式, 则默认情况下以该模式打开文件。
2 rb 它打开文件以只读二进制格式。文件指针位于文件的开头。
3 r+ 它打开文件以读取和写入两者。文件指针位于文件的开头。
4 rb+ 它打开文件以二进制格式读取和写入文件。文件指针位于文件的开头。
5 w 它打开文件以仅写。如果先前存在, 它将覆盖文件;如果不存在相同名称的文件, 它将创建一个新文件。文件指针位于文件的开头。
6 wb 它打开文件以仅以二进制格式写入。如果文件先前存在, 它将覆盖该文件;如果不存在同名文件, 则将创建一个新文件。文件指针位于文件的开头。
7 w+ 它将打开文件以进行写入和读取。它与r +的不同之处在于, 如果存在一个文件, 它将覆盖先前的文件, 而r +不会覆盖先前写入的文件。如果不存在文件, 它将创建一个新文件。文件指针位于文件的开头。
8 wb+ 它打开文件以二进制格式写入和读取。文件指针位于文件的开头。
9 a 它以追加模式打开文件。如果存在, 文件指针将位于先前写入文件的末尾。如果不存在同名文件, 它将创建一个新文件。
10 ab 它将以附加模式以二进制格式打开文件。指针存在于先前写入文件的末尾。如果不存在同名文件, 它将以二进制格式创建一个新文件。
11 a+ 它打开一个文件来追加和读取两者。如果文件存在, 文件指针将保留在文件末尾。如果不存在同名文件, 它将创建一个新文件。
12 ab+ 它打开一个文件以追加和读取二进制格式的文件。文件指针保留在文件末尾。

让我们看一个简单的示例, 以读取模式打开一个名为” file.txt”的文件(存储在同一目录中)并将其内容打印在控制台上。

例子

#opens the file file.txt in read mode
fileptr = open("file.txt", "r")

if fileptr:
	print("file is opened successfully")

输出

<class '_io.TextIOWrapper'>
file is opened successfully

close()方法

在文件上完成所有操作后, 我们必须使用close()方法通过python脚本将其关闭。一旦在文件对象上调用close()方法, 所有未写信息都会被销毁。

在python中打开文件后, 我们可以在文件系统中对文件进行外部任何操作, 因此, 一旦完成所有操作, 最好关闭文件。

下面给出了使用close()方法的语法。

fileobject.close()

考虑以下示例。

例子

# opens the file file.txt in read mode
fileptr = open("file.txt", "r")

if fileptr:
	print("file is opened successfully")

#closes the opened file
fileptr.close()

读取文件

要使用python脚本读取文件, python提供了read()方法。 read()方法从文件中读取一个字符串。它可以读取文本和二进制格式的数据。

下面给出了read()方法的语法。

fileobj.read(<count>)

此处, 计数是从文件开头开始要从文件读取的字节数。如果未指定计数, 则它可能会读取文件的内容直到结束。

考虑以下示例。

例子

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt", "r"); 

#stores all the data of the file into the variable content
content = fileptr.read(9); 

# prints the type of the data stored in the file
print(type(content)) 

#prints the content of the file
print(content) 

#closes the opened file
fileptr.close()

输出

<class 'str'>
Hi, I am

读取文件行

Python方便我们使用readline()函数逐行读取文件。 readline()方法从头开始读取文件的行, 即, 如果我们两次使用readline()方法, 则可以获取文件的前两行。

考虑下面的示例, 其中包含一个函数readline(), 该函数读取包含三行内容的文件” file.txt”的第一行。

例子

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt", "r"); 

#stores all the data of the file into the variable content
content = fileptr.readline(); 

# prints the type of the data stored in the file
print(type(content)) 

#prints the content of the file
print(content) 

#closes the opened file
fileptr.close()

输出

<class 'str'>
Hi, I am the file and being used as

遍历文件

通过遍历文件的各行, 我们可以读取整个文件。

例子

#open the file.txt in read mode. causes an error if no such file exists.


fileptr = open("file.txt", "r"); 

#running a for loop 
for i in fileptr:
	print(i) # i contains each line of the file

输出

Hi, I am the file and being used as 
an example to read a 
file in python.

写文件

要将一些文本写入文件, 我们需要使用具有以下访问模式之一的open方法打开文件。

答:它将追加现有文件。文件指针位于文件末尾。如果不存在文件, 它将创建一个新文件。

w:如果有文件存在, 它将覆盖文件。文件指针位于文件的开头。

考虑以下示例。

例子1

#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt", "a"); 

#appending the content to the file
fileptr.write("Python is the modern day language. It makes things so simple.")


#closing the opened file 
fileptr.close();

现在, 我们可以看到文件的内容已修改。

File.txt:

Hi, I am the file and being used as 
an example to read a 
file in python. 
Python is the modern day language. It makes things so simple.

例子2

#open the file.txt in write mode.
fileptr = open("file.txt", "w"); 

#overwriting the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")


#closing the opened file 
fileptr.close();

现在, 我们可以检查文件的所有先前写入的内容是否被我们传递的新文本覆盖。

File.txt:

Python is the modern day language. It makes things so simple.

创建一个新文件

可以通过使用以下访问模式之一(带有函数open())来创建新文件。 x:创建具有指定名称的新文件。它将导致错误的文件存在相同名称。

a:如果不存在指定名称的文件, 它将创建一个新文件。如果文件已经存在且具有指定名称, 它将内容附加到文件。

w:如果不存在指定名称的文件, 它将创建一个新文件。它将覆盖现有文件。

考虑以下示例。

例子

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt", "x"); 

print(fileptr)

if fileptr:
	print("File created successfully");

输出

File created successfully

与文件一起使用with语句

with语句是在python 2.5中引入的。 with语句在处理文件时很有用。 with语句用于要在一对语句之间插入一段代码的情况下使用。

下面提供了使用with语句打开文件的语法。

with open(<file name>, <access mode>) as <file-pointer>:
	#statement suite

使用with语句的优点在于, 无论嵌套块如何退出, 它都能保证关闭文件。

对于文件s, 总是建议使用with语句, 因为如果在嵌套的代码块中发生了中断, 返回或异常, 则它将自动关闭文件。它不会使文件损坏。

考虑以下示例。

例子

with open("file.txt", 'r') as f:
	content = f.read();
	print(content)

输出

Python is the modern day language. It makes things so simple.

文件指针位置

Python提供了tell()方法, 该方法用于打印文件指针所在的字节数。考虑以下示例。

例子

# open the file file2.txt in read mode
fileptr = open("file2.txt", "r")

#initially the filepointer is at 0 
print("The filepointer is at byte :", fileptr.tell())

#reading the content of the file
content = fileptr.read();

#after the read operation file pointer modifies. tell() returns the location of the fileptr. 

print("After reading, the filepointer is at:", fileptr.tell())

输出

The filepointer is at byte : 0
After reading, the filepointer is at 26

修改文件指针位置

在现实世界的应用程序中, 有时我们需要从外部更改文件指针的位置, 因为我们可能需要在各个位置读取或写入内容。

为此, python为我们提供了seek()方法, 使我们能够在外部修改文件指针的位置。

下面给出了使用seek()方法的语法。

<file-ptr>.seek(offset[, from)

seek()方法接受两个参数:

offset:它是指文件指针在文件中的新位置。

from:表示要从中移动字节的参考位置。如果将其设置为0, 则将文件的开头用作参考位置。如果将其设置为1, 则将文件指针的当前位置用作参考位置。如果设置为2, 则文件指针的末尾用作参考位置。

考虑以下示例。

例子

# open the file file2.txt in read mode
fileptr = open("file2.txt", "r")

#initially the filepointer is at 0 
print("The filepointer is at byte :", fileptr.tell())

#changing the file pointer location to 10.
fileptr.seek(10);

#tell() returns the location of the fileptr. 
print("After reading, the filepointer is at:", fileptr.tell())

输出

The filepointer is at byte : 0
After reading, the filepointer is at 10

Python操作系统模块

os模块为我们提供了文件处理操作中涉及的功能, 例如重命名, 删除等。

让我们看一下os模块的一些功能。

重命名文件

os模块为我们提供了rename()方法, 该方法用于将指定文件重命名为新名称。下面给出了使用rename()方法的语法。

rename(?current-name?, ?new-name?)

例子

import os;

#rename file2.txt to file3.txt
os.rename("file2.txt", "file3.txt")

删除文件

os模块为我们提供了remove()方法, 该方法用于删除指定的文件。下面给出了使用remove()方法的语法。

remove(?file-name?)

例子

import os;

#deleting the file named file3.txt 
os.remove("file3.txt")

创建新目录

mkdir()方法用于在当前工作目录中创建目录。下面给出了创建新目录的语法。

mkdir(?directory name?)

例子

import os;

#creating a new directory with the name new
os.mkdir("new")

更改当前工作目录

chdir()方法用于将当前工作目录更改为指定目录。

下面给出了使用chdir()方法的语法。

chdir("new-directory")

例子

import os;

#changing the current working directory to new 

os.chdir("new")

getcwd()方法

此方法返回当前工作目录。

下面给出了使用getcwd()方法的语法。

os.getcwd()

例子

import os;

#printing the current working directory 
print(os.getcwd())

删除目录

rmdir()方法用于删除指定的目录。

下面给出了使用rmdir()方法的语法。

os.rmdir(?directory name?)

例子

import os;

#removing the new directory 
os.rmdir("new")

将python输出写入文件

在python中, 存在将python脚本的输出写入文件的要求。

模块子进程的check_call()方法用于执行python脚本并将该脚本的输出写入文件。

以下示例包含两个python脚本。脚本file1.py执行脚本file.py并将其输出写入文本文件output.txt

file.py:

temperatures=[10, -20, -289, 100]
def c_to_f(c):
    if c< -273.15:
        return "That temperature doesn't make sense!"
    else:
        f=c*9/5+32
        return f
for t in temperatures:
    print(c_to_f(t))

file.py:

import subprocess

with open("output.txt", "wb") as f:
    subprocess.check_call(["python", "file.py"], stdout=f)

输出

50
-4
That temperature doesn't make sense!
212

文件相关方法

文件对象提供以下方法来在各种操作系统上操作文件。

SN Method Description
1 file.close() 它将关闭打开的文件。该文件一旦关闭, 就无法再读取或写入。
2 File.fush() 它刷新内部缓冲区。
3 File.fileno() 它返回底层实现用来从OS请求I / O的文件描述符。
4 File.isatty() 如果文件已连接到TTY设备, 则返回true, 否则返回false。
5 File.next() 它从文件返回下一行。
6 File.read([size]) 它读取指定大小的文件。
7 File.readline([size]) 它从文件中读取一行, 并将文件指针放置到新行的开头。
8 File.readlines([sizehint]) 它返回一个包含文件所有行的列表。它使用readline()函数读取文件, 直到出现EOF。
9 File.seek(offset [, from) 它将文件指针的位置修改为具有指定参考的指定偏移量。
10 File.tell() 它返回文件指针在文件中的当前位置。
11 File.truncate([size]) 它将文件截断为可选的指定大小。
12 File.write(str) 它将指定的字符串写入文件
13 File.writelines(seq) 它将字符串序列写入文件。

来源:

https://www.srcmini02.com/31136.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?