Can't write on a file - python

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.

Related

Problem with path when trying to write a file with a defined name given before by the code in Python

I'm having issues when I try to write a file in Python giving it a certain name and not only pathing it. Here is what I'm trying to do:
page_title=page.find('title')
raw_data_path ='output/'+page_title+'_raw.txt'
print (page_title)
with open(raw_data_path, 'w') as file:
file.write ()
When running this code, I receive the error [Errno 22] Invalid argument: 'output/myfile_raw.txt'
If instead of raw_data_path ='output/'+page_title+'_raw.txt' I put, for example, raw_data_path ='output/'+'_raw.txt' the code works well, so for some reason I can't combine the path with the name I'm trying to give the file.
I've searched that error and I see that it is a routing error, so it might be happening because when I want to add the page_title something happens with the path, but I can't see which is the mistake because it should be working.
Can someone give me some help with this issue?

File.write will not allow me to add to the textfile?

In my class, my instructor went over code to add names to a text file and to identify an IOError if one occurs. I copied the code he wrote exactly. It worked for him but not for me. The only difference I can think of is that he was using an older version of Python (it was an online video from 2017, doing online classes). I am currently using Python 3.8. Here is the code:
try:
file = open("namesList.txt", "a")
file.write("EOF")
except IOError:
print("IO Error")
file.close()
else:
print("EOF written successfully")
file.close()
I have tried pulling the code out of the try block to see if that works, but no errors popped up. It will still print "EOF written successfully" while in the try block and outside of it, but in the text file "EOF" does not show up.
I hope I explained it well enough, let me know if I need to clarify anything else. Thank you!
JessDee, the code is working for me as it is.
In any case, I think you should consider using the with statement when working with files.
It's cleaner, it's more pythonic. That way, you don't need to worry about closing the file. Python will do it for you.
I don't know if it will fix your problem, but it's something to consider.
This would be your code using with statement:
try:
with open("namesList.txt", "a+") as file:
file.write("EOF")
print("EOF written successfully")
except IOError:
print("IO Error")
Notice I used a+ instead of a. This means it will be opened in write/read mode.
Since we don't know the exact nature of your problem, I don't know if it will solve it, but it'll help you from now on. Good luck !

Why do I get a SyntaxError <unicode error> on my import statement? Should this not be simple?

Here's my first simple test program in Python. Without importing the os library the program runs fine... Leading me to believe there's something wrong with my import statement, however this is the only way i ever see them written. Why am I still getting a syntax error?
import os # <-- why does this line give me a syntax error?!?!?! <unicode error> -->
CalibrationData = r'C:/Users/user/Desktop/blah Redesign/Data/attempts at data gathering/CalibrationData.txt'
File = open(CalibrationData, 'w')
File.write('Test')
File.close()
My end goal is to write a simple program that will look through a directory and tabularize data from relevant .ini files within it.
Well, as MDurant pointed out... I pasted in some unprintable character - probably when i entered the URL.

python not writing to file for initial run

I have a super simple code and when run the first time it does not write to the file. But when run a second/multiple times later it writes to the file. The same thing happens when using "w" instead of "a" as well.
It also seems that the file is not closed after fh.close is run because I am unable to delete it - and a message appears saying that python is using the file. Any suggestions? Thanks!
fh = open("hello.txt","a")
fh.write("hello world again")
fh.close
fh.close doesn't call close, it just refers to the function. You need to do fh.close() to call the function.
you need to put the brackets after fh.close else you aren't actually calling the function, and if you are running interactively (i.e. with IDLE) then the interpreter keeps the file open.
so change your last line to:
fh.close()
James
The other posters are correct.
Also, I would suggest using the "with" statement when working with files, because then they will be automatically closed when your code goes out of scope.
with open("hello.txt","a") as fh:
fh.write("hello world again")
# Code that doesnt use the file continues here
If you use this, you never have to worry about closing your file. Even if runtime errors occur, the file will still always be closed.

IndexError: string index out of range - I cannot find answer anywhere but seems so easy

I'm using python 3.4
I have a .txt file and each line starts with an id number, then is followed by letters and numbers, for example...
012394 The big Project 1997 June Terry Smith
013894 Toms Project 1994 March Michaal Bach
and so on... I need to copy all lines that start with 01 to another file
when I use the following it keeps giving me the above error:
with open("old.txt","r") as mf, open("new.txt","w") as nf:
def dafunction():
mf = open ("old.txt", "r")
nf = open("new.txt","w")
for line in mf:
bat = str(line)
if bat.startswith(01):
nf.write(line)
dafunction()
mf.close()
nf.close()
I've tried using bat.startswith("01) and skipping setting bat variable and going straight to line.startswith(01), etc. and I keep getting the error.
Does anyone know what I'm doing wrong? or another way to accomplish objective?
Any help is greatly appreciated!
You have a lot of unnecessary code. Try:
with open("old.txt") as mf, open("new.txt", "w") as nf:
for line in mf:
if line.startswith('01'):
nf.write(line)
if bat.startswith(01): is not correct python syntax, you cannot use an `int`
You should just open your files inside the function.
def dafunction():
with open("old.txt","r") as mf:
with open("new.txt","w") as nf:
for line in mf:
if line.startswith("01"):
nf.write(line)
Ok yall, thanks for your help, you really helped me clean up my code, but it appears the problem was that the text file was saved from excel as unicode txt file and apparently the IDLE or python or whatever doesn't work well with unicode and it won't accurately compare without some other conversion code or something I guess.
I had the file saved as just txt tab delimited and then ran the code and it worked great! Thanks again for yall's help and I hope someone else gets some use from this sometime in the future!
tl:dr - File was saved in unicode and that was causing the problem.

Categories