我正在运行Python 3.5,使用JetBrains作为IDE。 如果我直接将其输入到控制台,则以下代码将创建具有正确文本的文件,但不是脚本。运行脚本时没有错误。
with open('test.txt', 'w', encoding='utf-8') as f:
print(123, True, 'blah', file=f)
答案 0 :(得分:0)
我测试了你的代码,它似乎工作。作为替代方案,您可以使用:
with open('test1.txt', 'w', encoding='utf-8') as f:
f.write("123 True blah")
由于我默认使用Python 2,我需要通过以下方式执行:
python3 myfile.py
3意味着它适用于Python 3而不是2.也许那就是你没有让它工作的地方?
以下是使用print函数执行此操作的另一种方法:
print("123, True, 'blah'", file=open('test1.txt', 'a'))
最后的'a'代表追加。
价: Directing print output to a .txt file in Python 3
由于该程序似乎起作用(至少对我来说)并且事实上我没有PyCharm。我只能为您提供3.5 print()的文档。也许这里的东西可以帮助你:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
"""
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
"""
答案 1 :(得分:0)
找到溶剂。 PyCharm有一个与python不同的默认文件夹,所以当我运行脚本时,默认位置与从JetBrains PyCharm中的控制台运行时的文件夹不同。当我写入已定义的文件路径时,它起作用了。