[英]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.