本文介绍了如何在 python 中转义正斜杠,以便 open() 将我的文件视为要写入的文件名,而不是要读取的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先说我不确定我的代码发生了什么;我对编程还很陌生.

Let me preface this by saying I'm not exactly sure what is happening with my code; I'm fairly new to programming.

我一直致力于为我的 Python CS 课程创建一个单独的期末项目,该项目每天检查我老师的网站,并确定自上次程序运行以来他是否更改了他网站上的任何网页.

I've been working on creating an individual final project for my python CS class that checks my teacher's website on a daily basis and determines if he's changed any of the web pages on his website since the last time the program ran or not.

我现在正在做的步骤如下:

The step I'm working on right now is as follows:

def write_pages_files():
    '''
    Writes the various page files from the website's links
    '''
    links = get_site_links()
    for page in links:
        site_page = requests.get(root_url + page)
        soup = BeautifulSoup(site_page.text)
        with open(page + ".txt", mode='wt', encoding='utf-8') as out_file:
            out_file.write(str(soup))

链接看起来像这样:

/site/sitename/class/final-code

我得到的错误如下:

with open(page + ".txt", mode='wt', encoding='utf-8') as out_file:
FileNotFoundError: [Errno 2] No such file or directory: '/site/sitename/class.txt'

如何使用这些类型的名称 (/site/sitename/nameofpage.txt) 编写站点页面?

How can I write the site pages with these types of names (/site/sitename/nameofpage.txt)?

推荐答案

你不能在 unix 或 windows 上的文件 basename 中有 /,你可以用 / 替换 /代码>.:

you cannot have / in the file basename on unix or windows, you could replace / with .:

page.replace("/",".") + ".txt"

Python 假定 /site 等.. 是一个目录.

Python presumes /site etc.. is a directory.

这篇关于如何在 python 中转义正斜杠,以便 open() 将我的文件视为要写入的文件名,而不是要读取的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:23