python程序中的文件路径错误

时间:2016-12-19 09:06:03

标签: 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,"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'

问题是什么以及如何解决,您的及时回复将受到高度赞赏

1 个答案:

答案 0 :(得分:-2)

如果您没有在文件夹“log”的父目录中启动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çoisFabre提到的,如果目录不存在,你必须在之前创建它:

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