如何在不同的位置保存python文件?

Naf*_*war 0 python

我在我的硬盘驱动器中使用python编程语言创建了一个文件.我使用的代码是:

file = open('test.txt','w')

file.write('Blah Blah')

file.close()
Run Code Online (Sandbox Code Playgroud)

此代码test.txt在硬盘驱动器中创建文件,但文件保存在项目的默认位置.我想将文件保存在其他位置,如桌面或其他位置.任何人都可以告诉我如何做到这一点.

我使用的是python 3.5

提前致谢,

Iro*_*ist 7

只需在字符串变量中指定位置,然后添加到要创建的文件名中open

import os
my_dir = 'C:\\Test\\My_Dir'
file_name = 'test.txt'
fname = os.path.join(my_dir, file_name)
file = open(fname,'w')
Run Code Online (Sandbox Code Playgroud)

  • _请_ 不要通过字符串连接来构建文件路径。很容易出错,就像你在这里一样(你可能并不真正想要`C:\\Test\\My_Dirtest.txt`)。[`os.path`](https://docs.python.org/3/library/os.path.html#module-os.path) 存在是有原因的。 (2认同)

The*_*CAL 6

打开文件时需要传递完整的绝对路径或相对路径:

file = open('/My/Example/Desktop/test.txt','w')
Run Code Online (Sandbox Code Playgroud)