编写一个pyhton程序来保存.txt文件中的数据,当创建文件路径时,它出错,路径中有“\”,为什么
程序:
#storage data in .txt file
def data_save_txt(type,data,id,name):
# get the date when storage data
date_storage()
#create the data storage directory
txt_parent_directory = os.path.join("dataset","txt",type,glovar.date)
directory_create(txt_parent_directory)
#write data in .txt
if type == "group_members":
txt_file_prefix = "gm"
elif type == "group_feed":
txt_file_prefix = "gf"
elif type == "public_figure_posts":
txt_file_prefix = "pfp"
elif "user_" in type:
txt_parent_directory = os.path.join("dataset", "txt", "user", type, glovar.date)
txt_file_prefix = type
txt_file_directory = os.path.join(txt_parent_directory,txt_file_prefix+"_"+time_storage()+"_"+id+"_"+name+".txt")
txt_file_object = open(txt_file_directory,"w",encoding="utf-8")
#to show the line number of stored data
line_number = 1
if isinstance(data,str):
txt_file_object.write(data)
elif isinstance(data,list):
group_info_data = ''
for i in range(len(data)):
for (k, v) in data[i].items():
group_info_data = group_info_data + str(line_number) + ") " + k + ':' + str(v) + ','
group_info_data += '\n'
line_number += 1
txt_file_object.write(group_info_data)
txt_file_object.close()
运行时,错误:
Traceback (most recent call last):
File "C:/Python/PyCharmProject/FaceBookCrawl/FBCrawl.py", line 255, in <module>
user_info_download.user_info_storage(user_id,user_info_type,u_access_token)
File "C:\Python\PyCharmProject\FaceBookCrawl\user_info_download.py", line 79, in user_info_storage
data_storage.data_save_txt(type,user_info,user_id,user_name)
File "C:\Python\PyCharmProject\FaceBookCrawl\data_storage.py", line 29, in data_save_txt
txt_file_object = open(txt_file_directory,"w",encoding="utf-8")
FileNotFoundError: [Errno 2] No such file or directory: 'dataset\\txt\\user\\user_friends\\20170121\\user_friends_20170121-124531_110286969468305_Du Bin.txt'
Process finished with exit code 1
指出
if "user_" in type:
txt_parent_directory = os.path.join("dataset", "txt", "user", type, glovar.date)
这句话错误,路径中有“\”,但是我使用os.path.join,为什么,谁可以帮我解决这个问题
答案 0 :(得分:1)
致电
txt_parent_directory = os.path.join("dataset", "txt", "user", type, glovar.date)
txt_file_directory = os.path.join(txt_parent_directory,txt_file_prefix+"_"+time_storage()+"_"+id+"_"+name+".txt")
您正在构建文件名字符串'dataset\txt\user\user_friends\20170121\user_friends_20170121-124531_110286969468305_Du Bin.txt'
双反斜杠只是Python显示某些特殊字符的方式。
但它不会创建实际的文件夹。运行类似
的内容os.makedirs()
在尝试创建文件之前,在目录上。
答案 1 :(得分:0)
我相信根据错误,您尝试在不存在的目录中创建文件。
即问题出在目录名称中,而不是文件名。