在Python中如何实现文件读写操作?
Python是一种高级编程语言,也是面向对象的语言。在Python中,我们可以使用内置的文件操作函数和模块来进行文件的读写操作。
1. 打开文件
在Python中打开文件需要使用open()函数,该函数接收两个参数, 个参数是文件的路径,第二个参数是打开文件的模式,常用的模式有:
- "r" : 以只读方式打开文件,如果文件不存在,会引发FileNotFoundError异常;
- "w" : 以写入方式打开文件,如果文件不存在,会创建一个新的文件;
- "a" : 以追加方式打开文件,如果文件不存在,会创建一个新的文件;
- "x" : 以独占的方式创建文件,如果文件已经存在,则会引发FileExistsError异常;
- "b" : 以二进制格式打开文件;
- "+" : 以读写模式打开文件。
例如,我们要打开一个名为test.txt的只读文本文件,可以使用以下代码:
file = open("test.txt", "r")
2. 读写文件
在Python中读写文件需要使用文件对象提供的read()、readline()、readlines()、write()和writelines()等方法。
- read(size=-1) : 从文件中读取指定的字节数或全部内容,如果没有给定size参数,则读取全部内容。例如:
with open("test.txt", "r") as file:
content = file.read()
- readline() : 从文件中读取一行数据。例如:
with open("test.txt", "r") as file:
line = file.readline()
- readlines() : 从文件中读取所有行,返回一个列表,每个元素代表一行数据。例如:
with open("test.txt", "r") as file:
lines = file.readlines()
- write(str) :向文件中写入一个字符串,返回写入的字符数。例如:
with open("test.txt", "w") as file:
file.write("Hello World!")
- writelines(list) : 向文件中写入一组字符串,每个字符串作为一个元素。例如:
lines = ['Python
', 'Java
', 'C++
']
with open('test.txt', 'w') as file:
file.writelines(lines)
3. 关闭文件
在Python中,操作文件后一定要记得关闭文件,可以使用文件对象提供的close()方法进行关闭。
例如:
file = open("test.txt", "r")
# 读文件操作
file.close()
另外,我们还可以使用with语句来对文件对象进行处理,这样就不必显式地调用close()方法了。在with语句块执行完毕时,文件自动关闭。例如:
with open("test.txt", "r") as file:
# 读文件操作
4. 示例代码
下面是一个文件读写的完整示例代码:
# 打开文件
with open("test.txt", "w") as file:
file.write("Python
")
file.write("Java
")
file.write("C++
")
# 读取文件
with open("test.txt", "r") as file:
content = file.read()
print(content)
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)
# 追加文件
with open("test.txt", "a") as file:
file.write("JavaScript
")
# 再次读取文件
with open("test.txt", "r") as file:
content = file.read()
print(content)
