python程序中的文件路径错误

python程序中的文件路径错误,python,Python,用pycharm编写一个python程序 该方案: log_file_name = os.path.join("log","log_"+glovar.date+".txt") print(log_file_name) if os.path.isfile(log_file_name): #if the log file has exist,append new content at the end of the file log_file = open(log_file_name,

用pycharm编写一个python程序

该方案:

log_file_name = os.path.join("log","log_"+glovar.date+".txt")
print(log_file_name)
if os.path.isfile(log_file_name):
    #if the log file has exist,append new content at the end of the file
    log_file = open(log_file_name,"a")
else:
    #if the log file not exist, create it and write the content in
    print(log_file_name)
    log_file = open("log\log_20161219.txt","w+")
错误是:

C:\Python\Python36\python.exe    C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py
log\log_20161219.txt
log\log_20161219.txt
Traceback (most recent call last):
File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 144, in     <module>
log_write("likes","success",user_count,user_addr_name)
File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 29, in   log_write
log_file = open("log\log_20161219.txt","w+")
FileNotFoundError: [Errno 2] No such file or directory: 'log\\log_20161219.txt'

问题是什么以及如何解决,我们将非常感谢您的及时回复

如果您没有在文件夹日志的父目录中启动python脚本,您必须使用绝对路径

您可以使用此选项删除相对路径:

root = r"C:\this\is\root\path"
log_folder = os.path.join(root, r"log")
log_file = log_file = os.path.join(root, "log","log20161219.txt") #edit JF-Fabre 
正如Jean-François Fabre所提到的,如果目录不存在,您必须在之前创建它:

if not os.path.exists(log_folder) :
    os.makedirs(log_folder)

找不到您的文件,因为您使用相对路径对其进行寻址-这是我对相对路径与绝对路径的标准答案:。若要添加注释,请执行以下操作:当前目录中不存在日志目录。这是错误的:root='C:\this\is\root\path'创建了一个带有表格和回车符的路径。当你不知道自己在哪里的时候创建一个目录也注定会失败。而log_file=os.path.joinlog_folder,log20161219.txt最好使用左根目录,因为如果他不需要log_folder,它仍然可以工作。好的,那么log_file=os.path.joinroot,log,log20161219.txt