首页 > 代码库 > Python文件IO
Python文件IO
Python文件IO
有如下文本内容,文件路径为D:\temp,文件名称为lyric.txt,
line1 Look ! line2 If U had one shotline3 One opportunityline4 To seize everything U ever wantedline5 One momentline6 Would U capture it ? line7 Or just let it slip
- 逐行读取,并输出
#coding=utf-8 import osfile_path = r‘D:\temp‘file_name = ‘lyric.txt‘#拼接文件路径与名称file_URI = os.path.join(file_path,file_name)print("file_URI-- " + file_URI)fd = open(file_URI, mode=‘r‘)#逐行读取文件内容for line in fd: #输出每行内容,每行行尾有换行符号 print(line)
输出结果,单独输出每行,包含此行的换行符:
file_URI-- D:\temp\lyric.txtline1 Look ! line2 If U had one shotline3 One opportunityline4 To seize everything U ever wantedline5 One momentline6 Would U capture it ? line7 Or just let it slip
- read(),读取全部内容
#coding=utf-8 import osfile_path = r‘D:\temp‘file_name = ‘lyric.txt‘file_URI = os.path.join(file_path,file_name)print("file_URI-- " + file_URI)fd = open(file_URI, mode=‘r‘)content = fd.read()print(content)
输出结果
file_URI-- D:\temp\lyric.txtline1 Look ! line2 If U had one shotline3 One opportunityline4 To seize everything U ever wantedline5 One momentline6 Would U capture it ? line7 Or just let it slip
- readlines(),读取全部内容,返回每行内容作为元素的列表
#coding=utf-8 import osfile_path = r‘D:\temp‘file_name = ‘lyric.txt‘file_URI = os.path.join(file_path,file_name)print("file_URI-- " + file_URI)fd = open(file_URI, mode=‘r‘)content_list = fd.readlines()print(content_list)
输出结果
file_URI-- D:\temp\lyric.txt[‘line1 Look ! \n‘, ‘line2 If U had one shot\n‘, ‘line3 One opportunity\n‘, ‘line4 To seize everything U ever wanted\n‘, ‘line5 One moment\n‘, ‘line6 Would U capture it ? \n‘, ‘line7 Or just let it slip‘]
Python文件IO
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。