【问题标题】:I am unable to create a file that does not exist and write to it using w+ mode我无法创建一个不存在的文件并使用 w+ 模式写入它
【发布时间】:2021-12-16 19:46:09
【问题描述】:

我正在尝试创建一个文件夹并向其中写入文件,即使该文件夹原本不存在,但我收到 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}')

【问题讨论】:

  • fighter 怎么样?它存在吗?
  • 它不存在,这就是为什么我使用 w+ 模式以便 python 可以自己创建并将文件写入它。
  • 等等。 filter 是一个目录。 w+ 打开一个文件进行读写。如果不存在,它将创建文件。但是如果路径中不存在则无法创建目录。
  • 我想我明白了,使用“os.makedirs()”效果很好。
  • 正是我所做的,请在答案部分查看。

标签: python windows web-scraping scrapy operating-system


【解决方案1】:
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}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2016-03-17
    • 2021-12-26
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多