我想打開要寫入的文件。在Python中打開文件夾中的文件?
with open(oname.text , 'w') as f:
,現在我想寫一個文件夾中的文件"Playlist"
我知道,我必須使用os.path
但我不知道如何使用它
TY所有
我想打開要寫入的文件。在Python中打開文件夾中的文件?
with open(oname.text , 'w') as f:
,現在我想寫一個文件夾中的文件"Playlist"
我知道,我必須使用os.path
但我不知道如何使用它
TY所有
path = os.path.join('Playlist', oname.text)
with open(path, 'w') as f:
...
如果您不確定當前目錄的'Playlist'
子目錄是否已存在,請將其前綴爲:
if not os.path.isdir('Playlist'):
if os.path.exists('Playlist'):
raise RuntimeError('Playlist exists and is a file, now what?!')
os.mkdir('Playlist')
這就提出了一個異常,如果'Playlist'
確實存在,但作爲一個文件,而不是一個目錄 - 處理這種異常情況下,如你所願,但除非你刪除或重命名文件,你不會是能夠把它當作目錄吧!
如果您想要的路徑有多級目錄,例如Play/List/Whatever
(爲防萬一您可以使用它),請使用os.makedirs
而不是os.mkdir
。
您可以使用os.chdir
函數更改當前工作目錄。
os.chdir('Playlist')
with open(oname.text , 'w') as f:
...
使用with
聲明和os.path.join
方法
dir_path = "/home/Playlist"
file_path = os.path.join('dir_path, "oname.txt")
content = """ Some content..."""
with open(file_path, 'wb') as fp:
fp.write(content)
OR
fp = open(file_path, "wb"):
fp.write(content)
fp.close()
'os.chdir( '播放列表')' –