文件路徑寫pyhton程序將數據保存在.txt文件時創建的文件路徑,它的錯誤,也有「\」的路徑,爲什麼「\」在os.path.join
程序:
#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,爲什麼,誰能幫我解決這個問題
雙斜槓是python顯示包含斜槓的字符串表示的常用方式。您的問題更可能是因爲您的文件不存在/您當前的目錄不是您認爲的目錄。 –
如果你打印('dataset \\ txt \\ user \\ user_friends \\ 20170121 \\ user_friends_20170121-124531_110286969468305_Du Bin.txt')''你得到'dataset \ txt \ user \ user_friends \ 20170121 \ user_friends_20170121-124531_110286969468305_Du Bin.txt ' - 注意,沒有雙反斜槓。你看到的是'\'轉義字符本身轉義的字符串表示。 – tdelaney