文件相关操作

时间:2018-03-30 18:01:41   收藏:0   阅读:202
# f = open(‘/Users/liuyan/Desktop/file.txt‘,‘r‘)
#
# first_line = f.readline()
#
# print(first_line)
#
# res = f.read()
#
# print(res)
#
# f.close()
问:怎么查看知道文件没有被关闭? --无法查看,建议使用 with 方法使用文件,可以不用考虑关闭文件。

建议使用如下方式打开文件使用。
with open(‘/Users/liuyan/Desktop/file.txt‘,‘r‘) as f:
for line in f:
print(line.strip())
#确认:打印一行后会打印一空行? 如果不想多打印一空行呢?使用line.strip()
with open(‘/Users/liuyan/Desktop/file.txt‘,‘r‘) as fr:
with open(‘/Users/liuyan/Desktop/file_bak.txt‘,‘w‘) as fw:
for line in fr:
fw.write(line) #写入未多写入一空行

原文:https://www.cnblogs.com/liuyanerfly/p/8677527.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!