告诉Python将.txt文件保存到Windows和M上的某个目录

2024-05-01 22:08:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何告诉Python在哪里保存文本文件?

例如,我的计算机正在桌面上运行Python文件。我希望它将所有文本文件保存在“文档”文件夹中,而不是桌面上。在这样的剧本里我该怎么做?

name_of_file = raw_input("What is the name of the file: ")
completeName = name_of_file + ".txt"
#Alter this line in any shape or form it is up to you.
file1 = open(completeName , "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

Tags: 文件ofthenameyouinputrawis
3条回答

打开文件句柄进行写入时,只需使用绝对路径。

import os.path

save_path = 'C:/example/'

name_of_file = raw_input("What is the name of the file: ")

completeName = os.path.join(save_path, name_of_file+".txt")         

file1 = open(completeName, "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

您可以选择将其与os.path.abspath()组合,如Bryan的回答中所述,以自动获取用户文档文件夹的路径。干杯!

一个小的更新。raw_input()在Python 3中被重命名为input()

Python 3 release note

使用os.path.join将指向Documents目录的路径与completeName(文件名?)由用户提供。

import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
    toFile = raw_input("Write what you want into the field")
    file1.write(toFile)

如果希望Documents目录与用户的主目录相对,可以使用以下内容:

os.path.join(os.path.expanduser('~'),'Documents',completeName)

其他人建议使用os.path.abspath。请注意,os.path.abspath不会将'~'解析到用户的主目录:

In [10]: cd /tmp
/tmp

In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'

相关问题 更多 >