创建文件并将其写入目录时出现问题

代码:


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()

回溯:


FileNotFoundError                         Traceback (most recent call last)

<ipython-input-13-83f8db356fab> in <module>

     10     ReportName=input("Numeric Summary Report Name.txt:")#Name Your Report ".txt"

     11     completeName = os.path.join(save_path, ReportName)

---> 12     f=open(completeName,"w+")

     13     f.write(lines)

     14     f.close()


FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Owner\\None\\testr.txt'

我试图将条件 .txt 文件写入目录中创建的文件夹,由于某种原因,该文件夹仅在我的 jupyter 笔记本中创建,而不是在所需的目录中,因此出现“目录未找到错误”。有谁知道我如何更改它在所需目录中创建文件夹的代码?先感谢您


慕尼黑5688855
浏览 87回答 2
2回答

素胚勾勒不出你

该错误是因为在第 8 行中您将 x 分配给 os.mkdir ,它不会返回文件名,因此请传递您想要在其中创建目录的路径。我认为这将是您正在寻找的答案:import os.pathlines="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 summaryif 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 语句是简化的:import os.pathlines="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 summaryif 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)

慕侠2389804

问题出在线路上x=os.mkdir(OutputFolder)os.mkdir没有显式返回值,因此x变为None.&nbsp;当您x插入时save_path,它被转换为字符串'None'。这创建了一个不存在的目录路径,因此 Python 无法在其中创建文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python