如何用Python写文件到文件?
我的尝试:
def test(src):
f = open('test.txt','w')
f.write("testabc")
for item in os.listdir(src):
s = os.path.join(src, item)
print s
f.write(s)
def main ():
src="/path/"
test(src)
if __name__ == '__main__':
main()
但它不起作用
答案 0 :(得分:4)
最好使用with
块来处理文件的关闭:
def test(src):
with open('test.txt','w') as f:
f.write("testabc")
for item in os.listdir(src):
s = os.path.join(src, item)
print s
f.write(s)
答案 1 :(得分:2)
您缺少f.close()
.....
for item in os.listdir(src):
s = os.path.join(src, item)
print s
f.write(s)
f.close() # <- add this line
.....