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

use*_*493 42 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()
Run Code Online (Sandbox Code Playgroud)

Aco*_*orn 58

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

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()
Run Code Online (Sandbox Code Playgroud)

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


unu*_*tbu 23

使用os.path.joinDocuments目录路径与completeName用户提供的(filename?)组合在一起.

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)
Run Code Online (Sandbox Code Playgroud)

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

os.path.join(os.path.expanduser('~'),'Documents',completeName)
Run Code Online (Sandbox Code Playgroud)

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

In [10]: cd /tmp
/tmp

In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
Run Code Online (Sandbox Code Playgroud)


Pau*_*mas 10

另一种不使用导入操作系统的简单方法是,

outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()
Run Code Online (Sandbox Code Playgroud)


Ash*_*her 8

如果要将文件保存到特定的 DIRECTORY 和 FILENAME,这里是一些简单的示例。它还检查目录是否已创建或尚未创建。

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()
Run Code Online (Sandbox Code Playgroud)

希望这对你有帮助!


小智 6

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

Python 3发行说明