2019-08-07 15:09:09 3214浏览
今天千锋扣丁学堂Python培训老师给大家分享一篇关于文件的读写操作实例分析详解,结合实例形式详细分析了Python常见的文件读写操作实现技巧及相关注意事项,下面我们一起来一下吧。
f = open('my_path/my_file.txt', 'r') # open方法会返回文件对象 file_data = f.read() # 通过read方法获取数据 f.close() # 关闭该文件
f = open('my_path/my_file.txt', 'w') f.write("Hello there!") f.close()
with open('my_path/my_file.txt', 'r') as f: file_data = f.read()
with open(camelot.txt) as song: print(song.read(2)) print(song.read(8)) print(song.read())
We 're the knights of the round table We dance whenever we're able
camelot_lines = [] with open("camelot.txt") as f: for line in f: camelot_lines.append(line.strip()) print(camelot_lines) # ["We're the knights of the round table", "We dance whenever we're able"]
def create_cast_list(filename): cast_list = [] #use with to open the file filename #use the for loop syntax to process each line #and add the actor name to cast_list with open(filename) as f: # use the for loop syntax to process each line # and add the actor name to cast_list for line in f: line_data = line.split(',') cast_list.append(line_data[0]) return cast_list cast_list = create_cast_list('./txts/flying_circus_cast.txt') for actor in cast_list: print(actor)
【关注微信公众号获取更多学习资料】 【扫码进入Python全栈开发免费公开课】