【Python/文本文件】使用Python读取文本文件的两种方式

【待读文件内容】

白日依山尽
黄河入海流
欲穷千里目
更上一层楼
wangzhihuan
2024年2月27日

【程序代码】

#encoding=utf-8

# 文本文件阅读方式1,路径写在变量中,斜杠需要转义,如不转义会出现OSError: [Errno 22] Invalid argument错误
filePath="C:\\Users\\ufo\\Desktop\\poem.txt"
with open(file=filePath,mode = 'r',encoding='utf-8') as infile1:
    for line in infile1:
        print("1."+line)

print("------------------------")

# 文本文件阅读方式2,路径写在参数里,路径前加r后无需转义
with open(r'C:\Users\ufo\Desktop\poem.txt',mode = 'r',encoding='utf-8') as infile2:
    for line in infile2:
        print("2."+line)

【控制台输出】

C:\hy\py\fileTest>python 1.py
1.白日依山尽

1.黄河入海流

1.欲穷千里目

1.更上一层楼

1.wangzhihuan

1.2024年2月27日
------------------------
2.白日依山尽

2.黄河入海流

2.欲穷千里目

2.更上一层楼

2.wangzhihuan

2.2024年2月27日

END

posted @ 2020-09-07 08:33  不朽的飞翔  阅读(301)  评论(0编辑  收藏  举报