Python自带的open()
函数能够轻松实现文件的读取操作。本文将通过简单易懂的实例,手把手教你如何使用Python读取文件内容。
1. 文件读取基本方法
假设我们电脑里有一个名为demofile.txt
的文本文件,内容如下:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
我们可以使用以下代码打开并读取该文件的内容:
f = open("demofile.txt", "r")
print(f.read())
f.close()
运行上述代码,终端将显示文件的全部内容:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
2. 打开指定位置的文件
如果文件不在当前目录中,而是保存在其他文件夹,则需明确指定完整路径:
f = open("D:\\myfiles\\welcome.txt", "r")
print(f.read())
f.close()
3. 只读取部分内容
read()
方法默认读取整个文件,也可以指定要读取的字符数量,例如只读取前5个字符:
f = open("demofile.txt", "r")
print(f.read(5))
f.close()
# 输出: Hello
4. 一行一行读取内容
如果只想读取一行,可以使用readline()
:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
# 输出: Hello! Welcome to demofile.txt
如果连续调用readline()
,可实现逐行读取:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
# 输出两行内容
5. 使用循环逐行读取
通过for循环遍历文件对象,可逐行读取文件内容:
f = open("demofile.txt", "r")
for line in f:
print(line)
f.close()
输出每一行内容,适合处理较大的文本文件。
6. 关闭文件的重要性
读取文件后务必调用close()
方法关闭文件。这是良好的编程习惯,能避免资源浪费及数据缓存引起的问题:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
7. 推荐使用with自动关闭文件
Python推荐使用with
语句来自动关闭文件,防止忘记手动关闭:
with open("demofile.txt", "r") as f:
print(f.read())
# 自动关闭文件
小结
通过以上示例,相信你已经学会了Python读取文件的基本操作。掌握这些技巧后,在日常编程中即可灵活运用。