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

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 !

Related

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.

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.

Deleting temporary files in python

I really would like to learn how submit questions using the cool formatting that seems to be available but it is not obvious to me just how to do that....
My question: My plan was to print "birdlist" (output from a listbox) to the file "Plain.txt" and then
delete the file so as to make it unavailable after the program exits. The problem with this is that for some reason "Plain.txt" gets deleted before the printing even starts...
The code below works quite well so long as I don't un-comment the last two lines in order to delete "Plain.txt... I have also tried to use the "tempfile" function that exists....it does not like me to send formatted string data to the temporary file. Is there a way to do this that is simple enough for my bird-brain to understand???
text_file = open("Plain.txt","w")
for name,place,time in birdlist:
text_file.write('{0:30}\t {1:>5}\t {2:10}\n'.format(name, place, time))
win32api.ShellExecute (0,"print",'Plain.txt','/d:"%s"' % win32print.GetDefaultPrinter (),".",0)
text_file.close()
#os.unlink(text_file.name)
#os.path.exists(text_file.name)
The problem is that Windows ShellExecute will just start the process and then return to you. It won't wait until the print process has finished with it.
If using the windows API directly, you can wait using the ShellExecuteEx function, but it doesn't appear to be in win32api.
If the user is going to be using your application for a while, you can keep a record of the file and delete it later.
Or you can write your own printing code so you don't have to hand it off to somebody else. See Print to standard printer from Python?
I had a similar issue with a program i'm writing. I was calling win32api.ShellExecute() under a for loop, to print a list of files and delete them afterwards. I started getting Notepad.exe popup messages on my screen telling me the file doesn't exist. After inserting some raw_input("press enter") statements to debug, i discovered that I needed a delay to avoid deleting the file too fast, so adding a time.sleep(.25) line after my ShellExecute("print",...) seemed to do the trick and fix it.
Might not be the cleanest approach, but I couldn't find anything more elegant for printing in Python that handles it better.
One thing i've been thinking about is using the 'Instance Handle ID' that is returned on successful ShellExecute() calls.. if its > 32 and >= 0 the call was successful. Maybe only run the delete if ShellExecute returns in that range, rather than trying to use an arbitrary time.sleep value. The only problem with this is it returns an exception if it's not successful and breaks out of the program.
Hope this helps!

Python MySQL UTF-8 encoding differs depending on order of execution

I recently inherited a python project and I've got some behavior I'm struggling to account for.
The code has two sections, it can import a file into the database, or it can dump the database to an output file. The import looks something like this:
def importStuff(self):
mysqlimport_args = ['mysqlimport', '--host='+self.host, '--user='+self.username, '--password='+self.password, '--fields-terminated-by=|', '--lines-terminated-by=\n', '--replace', '--local', self.database, filename, '-v']
output = check_output(mysqlimport_args)
The dump looks like this:
def getStuff(self):
db = MySQLdb.connect(self.host, self.username, self.password, self.database)
cursor = db.cursor()
sql = 'SELECT somestuff'
cursor.execute(sql)
records = cursor.fetchall()
cursor.close()
db.close()
return records
def toCsv(self, records, csvfile):
f = open(csvfile, 'wb')
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(['StuffId'])
count = 1
for record in records:
writer.writerow([record[0]])
f.close()
Okay not the prettiest python you'll ever see (style comments welcome as I'd love to learn more) but it seems reasonable.
But, I got a complaint from a consumer that my output wasn't in UTF-8 (the mysql table is using utf8 encoding by the way). Here's where I get lost, if the program executes like this:
importStuff(...)
getStuff(...)
toCsv(...)
Then the output file doesn't appear to be valid utf-8. When I break the execution into two different steps
importStuff(...)
then in another file
getStuff(...)
toCsv(...)
Suddenly my output appears as valid utf-8. Aside from the fact that I have a work around, I can't seem to explain this behavior. Can anyone shed some light on what I'm doing wrong here? Or is there more information I can provide that might clarify what's going on?
Thanks.
(python 2.7 in case that factors in)
EDIT: More code as requested. I've made some minor tweaks to protect the innocent such as my company, but it's more or less here:
def main():
dbutil = DbUtil(config.DB_HOST, config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD)
if(args.import):
logger.info('Option: --import')
try:
dbutil.mysqlimport(AcConfig.DB_FUND_TABLE)
except Exception, e:
logger.warn("Error occured at mysqlimport. Error is %s" % (e.message))
if(args.db2csv):
try:
logger.info('Option: --db2csv')
records = dbutil.getStuff()
fileutil.toCsv(records, csvfile)
except Exception, e:
logger.warn("Error Occured at db2csv. Message:%s" %(e.message))
main()
And that's about it. It's really short which is making this much less obvious.
The output I'm not sure how to faithfully represent, it looks something like this:
"F0NR006F8F"
They all look like more or less ASCII characters to me, so I'm not sure what problem they could be creating. Maybe I'm approaching this from the wrong angle, I'm currently relying on my text editor's best guess for what encoding a file is in. I'm not sure how I could best detect which character is causing it to stop reading my file as utf-8.
Dumbest answer of all time. The input data wasn't in UTF-8. Someone solved this by writing another sproc that would be called periodically to convert the non-utf-8 characters to utf-8. In the time it took me to break my code into two files and run them separately, the job ran. It just happened to run that way the 4-5 times I tried it leading to a false conclusion on my part. I'm now changing the read process to accommodate a non-utf-8 input source so I don't have a weird race condition hiding in the system. Sorry to have lead you all on this goosechase.

Python: How to ensure the last line of code has completed?

I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?
Okay..
picture.save(path, format='png')
time.sleep(1) #How to ensure the last step has finished
im = Image.open(path)
You do not need to do anything unless the previous operation is asynchronous. In your case, you should check picture.save's documentation to see if it specifically define as asynchronous. By default everything is synchronize. Each line will complete before it continues to next operation.
Seems like you just want to check is that there's a file at path before trying to open it.
You could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.
You really should just enclose the open operation in a try-except block:
try:
im = Image.open(path)
except [whatever exception you are getting]:
# Handle the fact that you couldn't open the file
im = None # Maybe like this..

Categories