Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “打印到文件”可从控制台工作,但在运行脚本时不起作用_Python_Python 3.x - Fatal编程技术网

Python “打印到文件”可从控制台工作,但在运行脚本时不起作用

Python “打印到文件”可从控制台工作,但在运行脚本时不起作用,python,python-3.x,Python,Python 3.x,我正在运行Python 3.5,使用JetBrains作为IDE。 下面的代码将创建一个具有正确文本的文件,如果我直接将其输入到console,而不是作为脚本。我在运行脚本时没有收到任何错误 with open('test.txt', 'w', encoding='utf-8') as f: print(123, True, 'blah', file=f) 我测试了你的代码,它似乎可以工作。作为替代方案,您可以使用: with open('test1.txt', 'w', encodi

我正在运行Python 3.5,使用JetBrains作为IDE。 下面的代码将创建一个具有正确文本的文件,如果我直接将其输入到console,而不是作为脚本。我在运行脚本时没有收到任何错误

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,而不是Python 2。也许这就是你不能让它发挥作用的地方


这里还有另一种使用打印功能的方法:

print("123, True, 'blah'", file=open('test1.txt', 'a'))
末尾的“a”代表append

参考:


因为这个计划似乎有效(至少对我来说),而事实上我没有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内的控制台运行时不同。相反,当我写入定义的文件路径时,它工作了。

当您从IDE执行此代码时,工作目录是什么?我让其余的代码工作,因此我认为它与执行无关。无论如何,我正在运行JetBrains Pycharm的代码。如果我添加一个打印('Hello world'),该部分将运行,没有错误,但也没有文件。没有PyCharm,因此无法在那里测试它。但也许我添加的信息会有用。祝你好运