【Python】文件写入操作

  • 文件的申明 open语句
    open('路径','模式',encoding='编码')
path = 'C:\\Users\\Administrator\\Desktop\\lianxi'
f = open(path+'\\test2.txt', 'w', encoding='utf8')
  • f.write(str)
  • f.writelines(list)
  • f.close()关闭文件
  • f.flush()直接映射在不关闭情况下,同样写入文件
  • with open(path+'\\test2.txt', 'w', encoding='utf8') ad f:不要关闭才看到写入文件。
path = 'C:\\Users\\Administrator\\Desktop\\lianxi'
f = open(path+'\\test2.txt', 'w', encoding='utf8')

f.write('hello word!') #根据光标位置,会覆盖文件。
f.close() #关闭之后才能显示写入的内容
print('finished!')

##################

path = 'C:\\Users\\Administrator\\Desktop\\lianxi'
with open(path+'\\test2.txt', 'w', encoding='utf8') ad f:
    f.write('ajfjl') #完成with内部操作以后,直接可以看到结果。
print('finished!')

##################

path = 'C:\\Users\\Administrator\\Desktop\\lianxi'
f = open(path+'\\test2.txt', 'w', encoding='utf8')
lst = ['a','b','c','d','e']

for i in range(len(str)):
    lst[i] = lst[i]+'\n'
    
f.writelines(lst)
f.close()

print('finished!')

##################

n = list(range(1,11))
m = ['a','b','c','d','e','f','g','h','i','j']

path = 'C:\\Users\\Administrator\\Desktop\\lianxi'
f = open(path+'\\test3.txt', 'w', encoding='utf8')

for i in range(len(n)):
    f.writelines([str(n[i]),',',str(m[i]),'\n'])
f.close()
print('finished!')

你可能感兴趣的:(【Python】文件写入操作)