亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創建文件并將其寫入目錄時出現問題

創建文件并將其寫入目錄時出現問題

慕尼黑5688855 2023-09-05 20:30:15
代碼: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:')    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 筆記本中創建,而不是在所需的目錄中,因此出現“目錄未找到錯誤”。有誰知道我如何更改它在所需目錄中創建文件夾的代碼?先感謝您
查看完整描述

2 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

該錯誤是因為在第 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 語句是簡化的:


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)


查看完整回答
反對 回復 2023-09-05
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

問題出在線路上

x=os.mkdir(OutputFolder)

os.mkdir沒有顯式返回值,因此x變為None. 當您x插入時save_path,它被轉換為字符串'None'。這創建了一個不存在的目錄路徑,因此 Python 無法在其中創建文件。



查看完整回答
反對 回復 2023-09-05
  • 2 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號