4

Python入门系列(十)一篇学会python文件处理 - 生活处处有BUG

 2 years ago
source link: https://www.cnblogs.com/bugs-in-life/p/16659305.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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")

注意:你只能删除空文件夹。

您的关注,是我的无限动力!

公众号 @生活处处有BUG


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK