簡體   English   中英

在當前目錄中寫入一個新文件夾並寫入文件

[英]Write a new folder in current directory and write file to it

我有以下腳本,它將輸入文件寫入新目錄。 我想更改它,因此不必顯式告訴它要寫入新目錄所在的目錄。 這種當前方法可以正常工作,但是需要用戶輸入路徑。 我看到了以下在當前目錄中創建的New文件夾,並以以下方式修改了我的腳本

import os

if not os.path.isdir('/home/bkwx97/python/test3/MINP'):
    os.mkdir('/home/bkwx97/python/test3/MINP')


with open('/home/bkwx97/python/test3/MINP/MINP','w') as f:

並得到了錯誤

“文件“ test3backupdir2.py”,第8行,以open('final_directory / MINP.txt','w')作為f:FileNotFoundError:[Errno 2]沒有這樣的文件或目錄:'final_directory / MINP.txt'”

我是否缺少簡單的東西? 還是我不能更改它,以便它將在當前目錄中寫入一個新文件夾,並將輸入內容寫入那里?

import os,os.path

current_directory = os.getcwd()
final_directory = os.path.join(current_directory,r'MINP')
if not os.path.exists(final_directory):
   os.makedirs(final_directory)

with open('final_directory/MINP.txt','w') as f:

也許您正在尋找的是:

with open('{}/MINP.txt'.format(final_directory),'w') as f:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM