创建文件并将文件写入目录的问题

问题描述

代码:

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无法在其中创建文件。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...