我有一个Python函数,用于将文本文件写入新文件夹或现有文件夹。问题是我第一次运行该函数时,当文件夹不存在时,我得到一个TypeError:对象类型' NoneType'没有len()。我第二次运行它,在创建文件夹后,它工作正常。
import os
def save_string_to_folder(new_folder, string):
folder_path = 'C:\Users\e6082493\Documents\Improve\Python\Scraping\Folder_%s' % (new_folder)
if not os.path.exists(folder_path):
folder_path = os.makedirs(folder_path)
join_path = os.path.join(folder_path, string)
join_path_finish = open(join_path, "w")
join_path_finish.close()
save_string_to_folder('new', 'TextFile.txt')
我会想到我的' if'声明将纠正此错误。我似乎无法弄清楚我失踪的那一步。谢谢。
这是追溯:
Traceback (most recent call last):
File "new_2.py", line 12, in <module>
save_string_to_folder('new', 'TextFile.txt')
File "new_2.py", line 7, in save_string_to_folder
join_path = os.path.join(folder_path, string)
File "C:\Python27\lib\ntpath.py", line 65, in join
result_drive, result_path = splitdrive(path)
File "C:\Python27\lib\ntpath.py", line 115, in splitdrive
if len(p) > 1:
TypeError: object of type 'NoneType' has no len()
PS C:\Users\e6082493\Documents\ImproveBKFS\Python\Scraping>
答案 0 :(得分:0)
函数os.makedirs
不会返回任何内容。将os.makedirs
函数调用的返回值分配给folder_path时,它现在包含<class 'NoneType'>
。以下代码应按预期工作。
import os
def save_string_to_folder(new_folder, string):
folder_path = 'C:\Users\e6082493\Documents\Improve\Python\Scraping\Folder_%s' % (new_folder)
if not os.path.exists(folder_path):
os.makedirs(folder_path) # Removed the assignment
join_path = os.path.join(folder_path, string)
join_path_finish = open(join_path, "w")
join_path_finish.close()
save_string_to_folder('new', 'TextFile.txt')
从第二次起,该文件夹已经创建,因此它不会进入if条件并删除变量folder_path
中的有效路径