在Python中,你可以使用内置的`open()`函数来打开文件,并通过不同的方法来读取或写入文件内容。下面是一些基本的文件操作示例:
读取文件内容
1. 使用`read()`方法一次性读取整个文件内容:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
2. 使用`readline()`方法逐行读取文件内容:
with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
3. 使用`readlines()`方法读取文件的所有行并返回一个列表:
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line, end='')
写入文件内容
1. 使用`write()`方法将内容写入文件:
with open('file.txt', 'w') as file:
file.write('Hello, World!')
2. 使用`append()`模式('a')在文件末尾添加内容:
with open('file.txt', 'a') as file:
file.write('This is a new line.\n')
注意事项
使用`with`语句可以确保文件在使用完毕后被正确关闭,即使在发生异常的情况下也能保证文件关闭。
文件操作时要注意编码问题,默认编码是`utf-8`,如果不是,可以显式指定。
文件路径可以是相对路径或绝对路径。
以上示例展示了Python中文件的基本读写操作。