我正在尝试使用 python 创建一个文本文件。这是我的代码-
import sys
import os
str1="a1.txt"
file1="Documents/Inbox/"
completeName=file1+str1
name1=os.path.abspath(completeName)
myfile = open(name1, 'w')
我想将文件 a1.txt 保存在我的主目录的文档文件夹中。使用上面的代码出现以下错误-
Traceback (most recent call last):
File "filesave.py", line 8, in <module>
myfile = open(name1, 'w')
FileNotFoundError: [Errno 2] No such file or directory: '/home/pulkit/Documents/Documents/Inbox/a1.txt'
请您参考如下方法:
此代码向您展示了如何检查路径是否存在并展开 ~ 以访问运行脚本的用户的主目录。
#!/usr/bin/python
import os
dpath=os.path.join(os.path.expanduser("~"),"Documents","Inbox")
if not os.path.exists(dpath):
os.makedirs(dpath)
fpath=os.path.join(dpath,"a1.txt")
open(fpath,"w").write("what ever you want")
