0

I am running Python 3.5, using JetBrains as the IDE. The following code will create a file with the correct text if I enter it directly to console, but not as a script. I get no errors when running the script.

with open('test.txt', 'w', encoding='utf-8') as f:
    print(123, True, 'blah', file=f)
Ullsokk
  • 697
  • 2
  • 11
  • 24
  • 4
    What is the working directory when you execute this code from the IDE? –  May 04 '18 at 07:55

2 Answers2

0

I tested your code and it seems to work. As an alternative you can use this:

with open('test1.txt', 'w', encoding='utf-8') as f:
    f.write("123 True blah")

Since I had Python 2 as default, I needed to execute it via:

python3 myfile.py

The 3 means it is for Python 3 and not 2. Maybe that's where you're not getting it to work?


Here is also another way to do it with the print function:

print("123, True, 'blah'", file=open('test1.txt', 'a'))

The 'a' at the end stands for append.

Ref: Directing print output to a .txt file in Python 3


Since the program seems to work (at least for me) and the fact I do not have PyCharm. I can only offer you the documentation for 3.5 print(). Maybe something here can help you out:

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.

"""
shafuq
  • 465
  • 6
  • 20
  • I get the rest of code to work, so I don't think it is related to the execution. In any case, I am running the code from JetBrains Pycharm. If I add a print('Hello world'), that part runs, no errors, but also no file. – Ullsokk May 04 '18 at 12:18
  • Don't have PyCharm, so can't test it there. But maybe the info I added can come of use. Good Luck! – shafuq May 04 '18 at 12:41
0

Found the sollution. PyCharm has a different default folder from python, so when I ran the script, default location would not be the same folder as when running from a console inside JetBrains PyCharm. When I wrote to a defined filepath instead, it worked.

Ullsokk
  • 697
  • 2
  • 11
  • 24