打开文件
使用 open 函数来打开文件。它接受两个参数:文件名和打开模式。打开模式可以是 'r'(读取)、'w'(写入)、'a'(追加)等。
# 打开文件以进行读取
file = open("example.txt", "r")
# 打开文件以进行写入,如果文件不存在则创建
file = open("example.txt", "w")
# 打开文件以进行追加
file = open("example.txt", "a")
读取文件内容
使用文件对象的 read 方法可以读取整个文件的内容,或者使用 readline 方法逐行读取。
# 读取整个文件
content = file.read()
print(content)
# 逐行读取
line = file.readline()
print(line)
写入文件
使用文件对象的 write 方法可以向文件中写入内容。
file = open("example.txt", "w")
file.write("Hello, this is a sample text.")
file.close()
关闭文件
使用 close 方法关闭文件。关闭文件是一个良好的习惯,可以释放资源。
file.close()
使用 with 语句
更安全的文件操作方式是使用 with 语句,它会在代码块结束时自动关闭文件。
with open("example.txt", "r") as file:
content = file.read()
# 在这里进行文件操作,不需要显式关闭文件
# 文件已经自动关闭
文件迭代器
文件对象是可迭代的,可以使用 for 循环逐行读取文件内容。
with open("example.txt", "r") as file:
for line in file:
print(line)
这只是 Python 文件 I/O 的入门,实际上还有更多高级的操作和异常处理机制,但这些基础知识足以让你开始在 Python 中进行文件处理。
转载请注明出处:http://www.zyzy.cn/article/detail/13330/Python 基础