3分钟掌握Python中处理文件的关键概念和功能

自由坦荡的智能 2025-02-19 01:12:52
打开文件:

要打开文件,可以使用 open() 函数。这需要两个参数——文件名和想要打开文件的模式(r 表示读取,w 表示写入,a 表示追加)。

通常打开任何文件有几种模式,这些模式是:r:read——————>读取文件w:write————→创建一个新文件a: Append — — — -> 将文件与现有文件追加b:binary——→读取二进制文件t:text————————>以文本模式打开文件+: update — → 以读写模式打开文件

读取文件:读取文件有不同的方法:read(size) — — — → 读取并返回指定的字节数。如果未指定大小,则会读取整个文件。readline() — — — -> 从文件中读取一行。readlines() — — → 从文件中读取所有行并将它们作为列表返回。

打开文件进行读取,从而以读取模式打开。

file = open('samplefile.txt', 'r')从文件中读取:

可以使用各种方法读取文件的内容。最常见的方法是read()。

sample = file.read() print(sample)写入文件:

要写入文件,以写入 (w) 或附加 (a) 模式打开它并使用 write() 方法。

#writing to a filewith open('example.txt', 'w') as file: file.write("Hello, this is a sample text.")附加到文件:

可以使用追加模式 (a) 将内容添加到现有文件而不覆盖其内容。

#Appending to a filewith open('example.txt', 'a') as file: file.write("\nThis is an additional line.")losing a File:Always remember to close the file using the close() method after performing operations on it.file.close()使用 with 语句:

在处理文件时使用 with 语句是一个很好的做法。执行代码块后,它会自动关闭文件。

with open('sample.txt', 'r') as file: sample= file.read() print(sample)

当块退出时,文件会自动关闭。

从文件中读取行:可以使用 readline() 方法一次读取一行,或使用 readlines() 将所有行读取到列表中。

with open('example.txt', 'r') as file: line = file.readline() print(line)lines = file.readlines() for line in lines: print(line)遍历文件:

可以使用 for 循环遍历文件的行。

with open('sample.txt', 'r') as file: for line in file: print(line)

0 阅读:0
自由坦荡的智能

自由坦荡的智能

感谢大家的关注