简体   繁体   中英

Can't write on a file

I am trying to write on a file from python on my terminal osX. I know that if the file doesn't exist, the write mode automatically creates a new file. Is that true? Out of the many times I tried it, there was one time that it partially worked. Can anyone tell me if my coding is wrong? Thank you. Code:

with open('mynewfile.txt', mode='w', encoding='utf-8') as a_file:
    a_file.write('these are my new files')
with open('mynewfile.txt', encoding='uff-8')
    print(a_file.read())

I can't even get pass the first line with that code. After I put in the first line, I get the invalid syntax error message.

Can someone tell me what I'm doing wrong? Do I need to have that file already? I also typed in the code using a try..except block exactly as my professor has it but it would not do it for me either.

You have syntax error in the third line, missed as a_file: and a wrong encoding uff-8 :

>>> with open('mynewfile.txt', encoding='utf-8') as a_file:
...     print(a_file.read())
these are my new files

Do I need to have that file already?

You don't need to have the file already as you are creating it.

I also typed in the code using a try..except block exactly as my professor has it but it would not do it for me either.

You can't use try..except with a syntax error.

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