首页 > 解决方案 > 我无法创建一个不存在的文件并使用 w+ 模式写入它

问题描述

我正在尝试创建一个文件夹并将文件写入其中,即使该文件夹最初不存在但我收到FileNotFoundError: [Errno 2] No such file or directory

我相信使用w+模式应该创建文件,无论它是否存在,然后写入它,但它似乎没有工作,我不断收到FileNotFoundError。我也尝试使用 a+ 或 r+ 但似乎都没有工作。

错误日志:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\fighter\\fighters-n.json'

ufcscraper.py:

page = response.url.split("&")[0][-1]
# a sample of the page url structure is: http://ufcstats.com/statistics/fighters?char=a&page=all
filename = f'fighters-{page}.json'

path = os.getcwd() # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\ufccrawler\\spiders'
new_path = path.split("\\")[0:-2] # ['C:', 'Users', 'Habib', 'Documents', 'Upwork_Projects', 'Stephanie-web-scraping', 'ufccrawler']
new_path = ("\\").join(new_path) + "\\fighter" # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\fighter'
completeName = os.path.join(new_path, filename) # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\fighter\\fighters-a.json'

with open(completeName, 'w+') as f:
    f.write(json.dumps(results, indent=2))
    f.close()
self.log(f'Saved file {completeName}')

标签: pythonwindowsweb-scrapingscrapyoperating-system

解决方案


page = response.url.split("&")[0][-1]
# a sample of the page url structure is: http://ufcstats.com/statistics/fighters?char=a&page=all
filename = f'fighters-{page}.json'

path = os.getcwd() # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\ufccrawler\\spiders'
new_path = path.split("\\")[0:-2] # ['C:', 'Users', 'Habib', 'Documents', 'Upwork_Projects', 'Stephanie-web-scraping', 'ufccrawler']
new_path = ("\\").join(new_path) + "\\fighter" # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\fighter'

# This fixes the issue for me by checking to see if the directory exist or not and the creates it if it doesn't exist
if not os.path.exists(new_path):
    os.makedirs(new_path)

completeName = os.path.join(new_path, filename) # 'C:\\Users\\Habib\\Documents\\Upwork_Projects\\Stephanie-web-scraping\\ufccrawler\\fighter\\fighters-a.json'

with open(completeName, 'w+') as f:
    f.write(json.dumps(results, indent=2))
    f.close()
self.log(f'Saved file {completeName}')

推荐阅读