Python编写文件读取和写入程序
发布时间:2023-12-04 16:20:38
在Python中,可以使用open()函数来实现文件的读取和写入操作。下面是文件读取和写入的基本语法:
1. 文件读取:
- 使用open()函数打开文件,指定文件路径和读取模式("r")。
- 使用read()函数读取文件内容,它会返回一个包含文件内容的字符串。
- 关闭文件,使用close()函数。
例子:
# 打开文件
file = open("example.txt", "r")
# 读取文件内容
content = file.read()
print(content)
# 关闭文件
file.close()
2. 文件写入:
- 使用open()函数打开文件,指定文件路径和写入模式("w")。
- 使用write()函数写入文件内容,参数为要写入的字符串。
- 关闭文件,使用close()函数。
例子:
# 打开文件
file = open("example.txt", "w")
# 写入文件内容
content = "Hello, World!"
file.write(content)
# 关闭文件
file.close()
除了上述的基本方法,还有一些其他常用的方法可以使用:
- 使用readline()函数逐行读取文件内容。
- 使用writelines()函数批量写入多行内容。
- 使用with关键字可以自动关闭文件。
例子:
# 逐行读取文件内容
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # 去除换行符
line = file.readline()
# 批量写入多行内容
lines = ["Line 1
", "Line 2
", "Line 3
"]
with open("example.txt", "w") as file:
file.writelines(lines)
以上就是文件的读取和写入的基本操作方法和相关使用例子。通过使用这些方法,可以方便地读取和写入文件的内容。
