繁体   English   中英

从控制台打印到文件有效,但运行脚本时无法打印

[英]print to file works from console, but not when running script

我正在运行Python 3.5,使用JetBrains作为IDE。 如果我直接将其输入到控制台(而不是作为脚本),则以下代码将创建带有正确文本的文件。 运行脚本时没有错误。

with open('test.txt', 'w', encoding='utf-8') as f:
    print(123, True, 'blah', file=f)

我测试了您的代码,它似乎可以工作。 或者,您可以使用以下方法:

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("123, True, 'blah'", file=open('test1.txt', 'a'))

末尾的“ a”代表追加。

参考: 在Python 3中将打印输出定向到.txt文件


由于该程序似乎有效(至少对我而言),而且我没有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.

"""

找到了解决方法。 PyCharm具有与python不同的默认文件夹,因此当我运行脚本时,默认位置将不同于从JetBrains PyCharm内部的控制台运行时的文件夹。 当我改为写一个定义的文件路径时,它起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM