简体   繁体   English

如何在Python中创建.txt文件? (Pycharm)

[英]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. 但是,我刚刚在PyCharm中尝试了此操作,但是它没有用。 I don't see any sign of the file LOOKHERE.txt 我没有看到文件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? 它与PyCharm对项目的使用有关系吗?

The text file is created in the pycharm project folder, like you suggested. 如您建议的那样,该文本文件在pycharm项目文件夹中创建。 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. 正如@ThanePlummer所提到的,只是想补充一点,通常在打开文件时使用with语句是一种更好的做法。 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. 使用r说明符和join命令执行此操作,以使其与平台无关。 It's best to use the with keyword when operating on files. 对文件进行操作时,最好使用with关键字。

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. 在PyCharm中,您可以指定工作目录以指向应执行程序的位置。 Open Edit Configuration by pressing Shift+Alt+F10 and then 0 or with Navigation Bar. Shift+Alt+F10 ,然后按0或使用导航栏,打开“ Edit Configuration Then in Working directory select project's path. 然后在Working directory选择项目的路径。

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

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