Python文件

文件处理是任何 Web 应用程序的重要组成部分。

Python 有几个函数用于创建、读取、更新和删除文件。


文件处理

在 Python 中处理文件的关键函数是 open()函数。

open()函数有两个参数; 文件名模式

打开文件有四种不同的方法(模式):

"r"- 读取 - 默认值。打开文件进行读取,如果文件不存在则出错

"a"- Append - 打开一个文件进行追加,如果文件不存在则创建该文件

"w"- 写入 - 打开文件进行写入,如果文件不存在则创建文件

"x"- 创建 - 创建指定文件,如果文件存在则返回错误

此外,您可以指定文件是否应作为二进制或文本模式处理

"t"- 文本 - 默认值。文本模式

"b"- 二进制 - 二进制模式(例如图像)


句法

要打开文件进行读取,指定文件名就足够了:

f = open("demofile.txt")

上面的代码与以下代码相同:

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

因为"r"for read 和 "t"for text 是默认值,所以不需要指定它们。

注意:确保文件存在,否则会出错。

在服务器上打开文件

假设我们有以下文件,位于与 Python 相同的文件夹中:

演示文件.txt

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

要打开文件,请使用内置open()函数。

open()函数返回一个文件对象,该对象有一个 read()读取文件内容的方法:

例子

f = open("demofile.txt", "r")
print(f.read())
运行示例 »

如果文件位于不同的位置,则必须指定文件路径,如下所示:

例子

在其他位置打开文件:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
运行示例 »

文件的只读部分

默认情况下,该read()方法返回整个文本,但您也可以指定要返回的字符数:

例子

返回文件的前 5 个字符:

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

读取行

您可以使用以下方法返回一行readline()

例子

读取文件的一行:

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"- 写入 - 将覆盖任何现有内容

例子

打开文件“demofile2.txt”并将内容附加到文件中:

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())
运行示例 »

例子

打开文件“demofile3.txt”并覆盖内容:

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"- Append - 如果指定的文件不存在,将创建一个文件

"w"- 写入 - 如果指定的文件不存在,将创建一个文件

例子

创建一个名为“myfile.txt”的文件:

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

结果:创建了一个新的空文件!

例子

如果文件不存在,则创建一个新文件:

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

删除文件

要删除文件,您必须导入 OS 模块,并运行其 os.remove()功能:

例子

删除文件“demofile.txt”:

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()方法:

例子

删除文件夹“myfolder”:

import os
os.rmdir("myfolder")

转载于:
https://www.w3schools.com/python/python_file_remove.asp

posted on 2022-03-28 15:54  -G  阅读(97)  评论(0)    收藏  举报

导航