[英]How to write a file to the desktop in 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
您需要指定要保存到的路径。 此外,利用os.path.join
( documentation )将路径和文件名放在一起。 您可以执行以下操作:
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
它没有写入随机目录。 它正在写入当前目录,即您从中运行它的目录。 如果希望它写入特定的目录(例如桌面),则需要将路径添加到文件名或切换当前目录。 首先完成
name = os.path.join('C:\Users\YourUser\Desktop', name)
第二个完成
os.chdir('C:\Users\YourUser\Desktop')
或无论桌面路径如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.