[英]How to write file to memory filepath and read from memory filepath in Python?
[英]How do I escape forward slashes in python, so that open() sees my file as a filename to write, instead of a filepath to read?
让我先说一下,我不确定我的代码发生了什么; 我对编程很新。
我一直在为我的python CS课程创建一个单独的最终项目,每天检查我的老师的网站,并确定自上次程序运行以来他是否更改了他网站上的任何网页。
我现在正在做的步骤如下:
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))
链接看起来类似于:
/网站/网站名称/等级/最终代码
我得到的错误如下:
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)编写网站页面?
你不能拥有/
在unix或windows上的文件basename中,你可以替换/
with .
:
page.replace("/",".") + ".txt"
Python假设/site
等..是一个目录。
在Unix / Mac OS上,对于中间斜杠,您可以使用:
将转换为/
在查看时,但会触发/
执行的子文件夹。
site/sitename/class/final-code
- > final-code
文件位于当前文件夹site:sitename:class:final-code
的site
文件夹中的sitename
文件夹中的class
文件夹中site:sitename:class:final-code
- > site/sitename/class/final-code
当前文件夹中的site/sitename/class/final-code
文件。
与问题的标题相关,虽然不是具体的,如果你真的希望你的文件名包含一些看起来像斜杠的东西,你可以使用unicode字符“/”( DIVISION SLASH ),也就是u'\∕'
。
这在大多数情况下都没用(并且可能令人困惑),但是当您希望包含在文件名中的概念的标准命名法包括斜杠时,它可能很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.