python - 我无法创建一个不存在的文件并使用 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}')
解决方案
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}')
推荐阅读
- python - 如何在 Python 3 中从磁盘读取和编辑列表?
- c++ - 应该如何在googletest中测试一个void函数
- r - 如何替换 dplyr::filter() 的空输出
- c - 如何使用“。”,“?”,“!”计算C中的句子数?
- java - Java iText PDF 注释/图章在 Chrome 和 Firefox(浏览器)上不可见
- firebase - Flutter:Future builder 不获取数据
- excel - 平均月报表 Excel
- java - 删除视图之间的额外空间
- .net-core - .Net core 2.2 API 版本控制和正确路由
- pega - 如何以 pega,YY-mm-dd 格式获取当前日期