Python不会写文本文件

问题描述 投票:-1回答:2

我写:

f = open("Textfile.txt","w")
f.write("This is a text file")
f.close()

但是当我打开文本文件时,什么都没写,有人知道为什么吗?

python text-files
2个回答
0
投票

在with语句中使用它应为您处理文件的关闭。这样可以解决问题吗?

 with open('Textfile.txt','w') as f:
        f.write('This is a text file')

0
投票

要将文件保存在所需位置,请使用完整路径。

with open('/home/me/project/testfile.txt', 'w') as outfile:
    outfile.write('content')

如果要将文件与脚本保存在同一目录中,则可以使用__file__

import os.path
path_of_script = os.path.dirname(__file__)
with open(os.path.join(path_of_script, 'testfile.txt', 'w') as outfile:
    outfile.write('content')
© www.soinside.com 2019 - 2024. All rights reserved.