使用python在给定的相对路径上创建文件
我的文件夹结构是:使用python在给定的相对路径上创建文件,python,file,Python,File,我的文件夹结构是:C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/ 使用下面的代码,我试图在ExceptionLogFiles文件夹中创建文件,如果文件Exceptionlog.txt不存在,如果文件存在,则打开文件并向文件写入一些文本。但由于某些原因,代码无法检测相对路径 请任何人帮我更正代码: fileDir = 'C:/Users/Desktop/SampleTestFiles' filename = os.p
C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/
使用下面的代码,我试图在ExceptionLogFiles
文件夹中创建文件,如果文件Exceptionlog.txt
不存在,如果文件存在,则打开文件并向文件写入一些文本。但由于某些原因,代码无法检测相对路径
请任何人帮我更正代码:
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'
但是,即使您从字符串中删除了。\
,这些反斜杠在没有转义的情况下也不会变成字符串中的文字反斜杠
试试这个(注意反斜杠是加倍的,以便转义反斜杠,这是转义字符!)
看起来你在找 结果:
C:/Users/Desktop/SampleTestFiles/../ExceptionLogFiles/ExceptionLog.txt
C:/Users/Desktop/ExceptionLogFiles/ExceptionLog.txt
您可以使用“with open('path','a+')作为f”,无论文件是否存在,您都可以在其中写入内容
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