簡體   English   中英

使用python在給定的相對路徑創建文件

[英]Create file at given relative path using python

我的文件夾結構是: C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/

使用下面的代碼,如果文件Exceptionlog.txt不存在,我試圖在ExceptionLogFiles文件夾中創建文件,如果文件存在,則打開該文件並向該文件寫入一些文本。 但由於某種原因,代碼無法檢測到相對路徑。

請任何人都可以幫助我更正代碼:

fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, '\..\ExceptionLogFiles\ExceptionLog.txt')


#print(filename) gives: C:/Users/Desktop/SampleTestFiles/../ExceptionLog.txt
if os.path.exists(filename):
    print(filename, 'exists')
    #Open file and write something to the file
    f = open(file, 'w')
    f.write("Exception Text")
    f.close()
else:
    print('file not exists')
    #Create File and Write something to the file.
    f = open(file, 'w+')
    f.write("Exception Text")
    f.close()

你試圖做的有點像這樣,以一種類似加法的方式

(
C:/Users/Desktop/SampleTestFiles
+ 
.. (which is up one directory)
)
+ ExceptionLogFiles\ExceptionLog.txt

“帶括號的”添加實際上會解析為C:/Users/Desktop/ ,我們將ExceptionLogFiles\\ExceptionLog.txt'添加到其中。 所以我們會查看:`C:/Users/Desktop/ExceptionLogFiles\\ExceptionLog.txt'

但是,即使您從字符串中刪除了..\\ ,這些反斜杠也不會在您不轉義它們的情況下成為字符串中的字面反斜杠。

試試這個(並注意反斜杠加倍以逃避反斜杠,這是轉義字符!)

fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, 'ExceptionLogFiles\\ExceptionLog.txt')

看起來你正在尋找normpath

import os

fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, '../ExceptionLogFiles/ExceptionLog.txt')
print(filename)
print(os.path.normpath(filename))

結果:

C:/Users/Desktop/SampleTestFiles/../ExceptionLogFiles/ExceptionLog.txt
C:/Users/Desktop/ExceptionLogFiles/ExceptionLog.txt

您可以使用“with open('path','a+') as f”,無論文件存在與否,您都可以向其中寫入內容。

暫無
暫無

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

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