简体   繁体   中英

How to create a .txt file in Python? (Pycharm)

In a previous post, I asked how to create a new file to be written in if it didn't already exist. However, I've just tried this in PyCharm, and it's not working. I don't see any sign of the file LOOKHERE.txt

my_list = [i**2 for i in range(1,11)]

openfile = open('LOOKHERE.txt', 'w')
for item in my_list:
    openfile.write(str(item) + "\n")
openfile.close()

What am I doing wrong? Could it have anything to do with PyCharm's use of projects?

The text file is created in the pycharm project folder, like you suggested. If you want it to go elsewhere, like your desktop for instance, do this:

f = open('path_to_desktop/file.txt', 'w')

Note: I just tested this on my own system. I was able to get the project path by right-clicking the folder in the project window(on the right), and clicking 'copy path' from the menu that pops up.

EDIT: I assume since you accepted my answer, that this worked out for you eventually(though please, any other questions, do comment). Just wanted to add, as @ThanePlummer mentioned, that it's generally better practice to use the with statement when opening files. One reason being that your files get auto-closed for you! Google it up ;)

First you should explicitly specify the path. Do this using the r specifier and the join command so that it is platform independent. It's best to use the with keyword when operating on files.

import os

my_path = r'my/longpath/here' # forward slash works on all systems

my_list = [i**2 for i in range(1,11)]

with open(os.path.join(my_path, 'subdir', 'LOOKHERE.txt'), 'w') as fh:
    for item in my_list:
        openfile.write(str(item) + "\n")

In PyCharm you can specify working directory to point the location where program should be executed. Open Edit Configuration by pressing Shift+Alt+F10 and then 0 or with Navigation Bar. Then in Working directory select project's path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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