How can I hide slashes in python so that open () sees my file as the name of the file to write, and not the path to the file to read?

Let me state this by saying that I am not quite sure what is going on with my code; I am new to programming.

I am working on creating a separate final project for my python CS class, which checks my teacher website daily and determines if it has changed any web pages on its website since the last time the program was launched or not.

The step I'm currently working on is as follows:

def write_pages_files(): ''' Writes the various page files from the website 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)) 

The links look something like this:

/ site / site_name / class / final code

And the error I get is as follows:

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

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

+8
python
source share
3 answers

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

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

Python assumes /site , etc. is a directory.

+5
source share

On Unix / Mac OS, for middle slashes, you can use : which will be converted to / when viewed, but launches subfolders that / does.

site/sitename/class/final-code β†’ final-code in the class folder in the sitename folder in the site folder in the current site:sitename:class:final-code folder site:sitename:class:final-code β†’ site/sitename/class/final-code in the current folder.

+2
source share

Due to the title of the question, although not specific, if you really want your file names to include something like a slash, you can use the unicode character "/" ( DIVISION SLASH ), aka u'\u2215' .

This is not useful in most cases (and can be confusing), but it can be useful when the standard concept nomenclature that you want to include in the file name includes slashes.

0
source share

All Articles