简体   繁体   中英

Python 2.7 File Handling saving username

Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help

You need to be carefull about special chars "\\":

fileloc = "N:\\Documents\\1) Subjects, Word and Powerpoint\\GCSE Computing\\NEA\\GCSE 2017\\users\\\\" filename = fileloc+"newname"+".txt" print filename N:\\Documents) Subjects, Word and Powerpoint\\GCSE Computing\\NEA\\GCSE 2017\\users\\newname.txt

I used "newname" as a string here, you can set it and change as a var.

By ending your string with a \\ you're escaping the next character (which is " ) hence the string is not terminated. Beware that you're also escaping the character next to every \\

What you probably want

fileloc = "N:\\Documents\\1) Subjects, Word and Powerpoint\\GCSE Computing\\NEA\\GCSE 2017\\users\\"

learn more about character escape here: https://en.wikipedia.org/wiki/Escape_character

Using forward slashes will work under Windows.

fileloc = "N:/Documents/1) Subjects, Word and Powerpoint/GCSE Computing/NEA/GCSE 2017/users/"

Alternatively you can use a raw string literal by prefixing an r .

fileloc = r"N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM