如何在python中将文件写入桌面?

时间:2016-02-15 17:39:01

标签: python

当我将此代码转换为可执行文件时,编写文件的功能可以正常工作,但它会写入随机目录。我不知道如何让它写入我的桌面,就像它是普通的python文件一样。

这是我的代码,

def write():
        print('Creating a new file')

        name = raw_input('Enter a name for your file: ')+'.txt'  # Name of text file coerced with +.txt

        try:
            file = open(name,'w')   # Trying to create a new file or open one
            file.close()

        except:
            print('Something went wrong! Cannot tell what?')
            sys.exit(0) # quit Python

2 个答案:

答案 0 :(得分:1)

您需要指定要保存到的路径。此外,使用os.path.joindocumentation)将路径和文件名放在一起。你可以这样做:

from os.path import join
def write():
        print('Creating a new file')
        path = "this/is/a/path/you/want/to/save/to"
        name = raw_input('Enter a name for your file: ')+'.txt'  # Name of text file coerced with +.txt

        try:
            file = open(join(path, name),'w')   # Trying to create a new file or open one
            file.close()

        except:
            print('Something went wrong! Cannot tell what?')
            sys.exit(0) # quit Python

答案 1 :(得分:0)

它不是写入随机目录。它写入当前目录,即您运行它的目录。如果要将其写入特定目录(如桌面),则需要添加文件名路径或切换当前目录。第一个是用

完成的
name = os.path.join('C:\Users\YourUser\Desktop', name)

第二个用

完成
os.chdir('C:\Users\YourUser\Desktop')

或者桌面的路径是什么。