如何解决创建文件并将文件写入目录的问题
代码:
jsonPost["_created_at"] = ["__type": "Date","iso": "2020-09-23T13:31:08.877Z"]
回溯:
import os.path
lines="hiya"
Question_2=input("Do you want a numeric summary report for? Y/N:")#If you input Y it will generate a single .txt file with number summary
if Question_2 == 'Y' or 'y':
print("Q2-YES")
OutputFolder = input('Name:')
x = os.mkdir(OutputFolder)
save_path = r'C:\Users\Owner\{}'.format(x)
ReportName=input("Numeric Summary Report Name.txt:")#Name Your Report ".txt"
completeName = os.path.join(save_path,ReportName)
f=open(completeName,"w+")
f.write(lines)
f.close()
我试图将条件.txt文件写入目录中的已创建文件夹,由于某种原因,该文件夹仅在我的jupyter笔记本中创建,而不在所需目录中创建,因此出现“找不到目录错误”。有谁知道我如何更改在所需目录中创建文件夹的代码?预先谢谢你
解决方法
错误是因为在第8行中,您将x分配给了不返回文件名的os.mkdir,因此传递了您要在其上创建目录的路径。
这就是我想找到的答案:
import os.path
lines="hiya"
Question_2=input("Do you want a numeric summary report for? Y/N:")#If you input Y it will generate a single .txt file with number summary
if Question_2 == 'Y' or 'y':
print("Q2-YES")
OutputFolder=input('Name:')
save_path = r'C:\Users\Owner\{}'.format(OutputFolder)
os.mkdir(save_path)
ReportName=input("Numeric Summary Report Name.txt:")#Name Your Report ".txt"
completeName = os.path.join(save_path,ReportName)
f=open(completeName,"w+")
f.write(lines)
f.close()
我也做了一些更改以简化此代码。最主要的是使用with statement来简化:
import os.path
lines="hiya"
Question_2 = input("Do you want a numeric summary report for? Y/N:") # If you input Y it will generate a single .txt file with number summary
if Question_2 == 'Y' or 'y':
OutputFolder = input('Enter Output folder name: ')
save_path = os.path.abspath('C:\\Users\\owner\\{}'.format(OutputFolder))
os.mkdir(save_path)
ReportName = input("Name of report file:") + ".txt" # Name Your Report ".txt"
completeName = os.path.join(save_path,ReportName)
with open(completeName,"w") as output_file:
output_file.write(lines)
,
问题出在那
x=os.mkdir(OutputFolder)
os.mkdir
没有显式返回值,因此x
成为None
。当您将x
插入save_path
时,它被转换为字符串'None'
。这样就创建了一个目录的路径,该目录不存在,因此Python无法在其中创建文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。