关于python:Python入门系列十一篇学会python文件处理

文件解决

在Python中解决文件的要害函数是open()函数。有四种不同的办法(模式)来关上一个文件

“r” – 读取 – 默认值。关上一个文件进行读取,如果文件不存在则出错。

“a” – Append – 关上一个文件进行追加,如果文件不存在则创立该文件

“w” – 写 – 关上一个文件进行写入,如果不存在则创立文件

“x” – 创立 – 创立指定的文件,如果文件存在则返回谬误。

此外,你还能够指定文件应以二进制或文本模式解决。

“t” – 文本 – 默认值。文本模式

“b” – 二进制 – 二进制模式(如图像)。

要关上一个文件进行浏览,只需指定文件的名称即可

f = open("demofile.txt")

下面的代码与

f = open("demofile.txt", "rt")

因为 “r “代表读取,”t “代表文本,是默认值,你不须要指定它们。

留神:确保该文件存在,否则你会失去一个谬误。

读取文件

open()函数返回一个文件对象,它有一个read()办法用于读取文件的内容

f = open("demofile.txt", "r")
print(f.read())

如果文件位于一个不同的地位,你将不得不指定文件门路,像这样

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

只读文件的局部内容

f = open("demofile.txt", "r")
print(f.read(5))

读取行

f = open("demofile.txt", "r")
print(f.readline())

通过调用readline()两次,您能够读取前两行

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

通过遍历文件的各行,您能够逐行读取整个文件

f = open("demofile.txt", "r")
for x in f:
  print(x)

最好总是在解决完文件后将其敞开。

f = open("demofile.txt", "r")
print(f.readline())
f.close()

留神:您应该始终敞开您的文件,在某些状况下,因为缓冲,在您敞开文件之前,可能不会显示对文件所做的更改。

写入文件

要写入现有文件,必须向open()函数增加参数

“a” – 附加 – 将附加到文件的开端。

“w” – 写 – 将笼罩任何现有内容

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

留神:”w “办法将笼罩整个文件。

要在Python中创立一个新的文件,应用open()办法,并带有以下参数之一

“x” – 创立 – 将创立一个文件,如果该文件存在则返回谬误

“a” – 附加 – 如果指定的文件不存在将创立一个文件

“w” – 写 – 如果指定的文件不存在,将创立一个文件

f = open("myfile.txt", "w")

删除文件

要删除一个文件,你必须导入OS模块,并运行其os.remove()函数

import os
os.remove("demofile.txt")

查看文件是否存在

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

要删除整个文件夹,应用os.rmdir()办法

import os
os.rmdir("myfolder")

留神:你只能删除空文件夹。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理