Check to see if file exists is failing - python

Here is my code:
# header.py
def add_header(filename):
header = '"""\nName of Project"""'
try:
f = open(filename, 'w')
except IOError:
print "Sorry could not open file, please check path"
else:
with f:
f.seek(0,0)
f.write(header)
print "Header added to", filename
if __name__ == "__main__":
filename = raw_input("Please provide path to file: ")
add_header(filename)
When I run this script (by doing python header.py), even when I provide a filename which does not exist it does not return the messages in the function. It returns nothing even when I replace the print statements with return statements. How would I show the messages in the function?

I believe you are always creating the file. Therefore, you won't see a file not there exception. It does not hurt to put a write or file open write under try except, because you might not have privileges to create the file.
I have found with statements like try except and else to test those at the Python command line, which is a very excellent place to work out cockpit error, and I'm very experienced at generating a lot of cockpit error while proving out a concept.
The fact you're using try except is very good. I just have to go review what happens when a logic flow goes through one of them. The command line is a good place to do that.

The correct course of action here is to try and read the file, if it works, read the data, then write to the file with the new data.
Writing to a file will create the file if it doesn't exist, and overwrite existing contents.
I'd also note you are using the with statement in an odd manner, consider:
try:
with open(filename, 'w') as f:
f.seek(0,0)
f.write(header)
print("Header added to", filename)
except IOError:
print("Sorry could not open file, please check path")
This way is more readable.
To see how to do this the best way possible, see user1313312's answer. My method works but isn't the best way, I'll leave it up for my explanation.
Old answer:
Now, to solve your problem, you really want to do something like this:
def add_header(filename):
header = '"""\nName of Project"""'
try:
with open(filename, 'r') as f:
data = f.read()
with open(filename, 'w') as f:
f.write(header+"\n"+data)
print("Header added to"+filename)
except IOError:
print("Sorry could not open file, please check path")
if __name__ == "__main__":
filename = raw_input("Please provide path to file: ")
add_header(filename)
As we only have the choices of writing to a file (overwriting the existing contents) and appending (at the end) we need to construct a way to prepend data. We can do this by reading the contents (which handily checks the file exists at the same time) and then writing the header followed by the contents (here I added a newline for readability).

This is a slightly modified version of Lattywares solution. Since it is not possible to append data to the beginning of a file, the whole content is read and the file is written anew including your header. By opening the file in read/write mode we can do both operations with the same file handler without releasing it. This should provide some protection against race conditions.
try:
with open(filename, 'r+') as f:
data = f.read()
f.seek(0,0)
f.write(header)
f.write(data)
#f.truncate() is not needed here as the file will always grow
print("Header added to", filename)
except IOError:
print("Sorry, could not open file for reading/writing")

this script opens a file in "w" mode (write mode),which means once the file dose not exist,it will be created. So No IOError.

Related

Python 3.6 - file.write() not actually writing

In case you didn't catch it in the title, this is Python 3.6
I'm running into an issue where I was able to write to a file, and now I cannot. The crazy thing is that this was working fine earlier.
I'm trying to either append my file if it exists, or write to a new file if it doesn't exist.
main_area_text represents the div tag text below
<div id="1131607" align="center"
style="width:970px;padding:0px;margin:0px;overflow:visible;text-
align:center"></div>
and below is my code:
main_area_text = #this is equal to the html text above
#I've verified this with a watch during debugging
#But this doesn't actually matter, because you can put
#anything in here and it still doesn't work
html_file_path = os.getcwd() + "\\data\\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
actual_file = open(html_file_path, "a")
actual_file.write(main_area_text)
else:
print("File does not exist!")
actual_file = open(html_file_path, "w")
actual_file.write(main_area_text)
Earlier, in it's working state, I could create/write/append to .html and .txt files.
NOTE: If the file doesn't exist, the program still creates a new file... It's just empty.
I'm somewhat new to the python language, so I realize it's very possible that I could be overlooking something simple. (It's actually why I'm writing this code, to just familiarize myself with python.)
Thanks in advance!
Since you're not closing your file, the data isn't being flushed to disk. Instead try this:
main_area_text = "stuff"
html_file_path = os.getcwd() + "\\data\\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
with open(html_file_path, "a") as f:
f.write(main_area_text)
else:
print("File does not exist!")
with open(html_file_path, "w") as f:
f.write(main_area_text)
The python with statement will handle flushing the data to disk and closing the data automatically. It's generally good practice to use with when handling files.

read files in python 3

I'm learning how to read files and I want to know why this is happening and how to fix it. I made a .txt file just for practicing this and I have it in my documents. When I run the code though it tells me.
Errno2 no such file or directory: jub.txt
I have tried listing it as C:\Users and so on as well. I have watched tons of tutorials. Can some one please explain this to me so I can get it to work.
print ("Opening and closing a file")
text_file = open("jub.txt", "r")
print (text_file('jub.txt'))
text_file.close()
First check that your file exists in current directory, you can add this simple validation.
Secondly use with wrapper, it will close file for you after you exit this block. Thirdly: You read from file using read and readlines methods.
print ("Opening and closing a file")
f_name = "jub.txt"
if not os.path.exists(f_name):
print 'File %s does not exist'%f_name
return
with open(f_name , "r") as text_file:
print (text_file.read())
For your path to be more precise, mayby use full system path, and not relative. Example: '/home/my_user/doc/myfile.txt'
Just to complement the code provided by Beri, I would rather use a try/except statement, and the new-style string formatting:
print("Opening and closing a file")
f_name = 'jub.txt'
try:
with open(f_name, 'r') as text_file:
print(text_file.read())
except FileNotFoundError:
print("File {} does not exist".format(f_name))
By the way I would recommend reading directly from the official Python doc, it's pretty clear and concise:
https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files

Don't save empty file

I create a new text file with f = open('file.txt', 'w'). Then, as I go about to get stuff to write on it, there is a problem and I need to exit without actually writing anything.
However, the file is still created, but empty. Is there a way to keep the file from being saved in case nothing is going to be written on it, or do I have to explicitly delete it in case something goes wrong?
You can use atexit to simulate this behavior, but there's probably a Better Way out there somewhere.
import atexit
def safety_trigger():
try:
os.remove(FILENAME)
except FileNotFoundError:
pass
atexit.register(safety_trigger)
with open(FILENAME,'w') as f:
# do your
# file operations
atexit.unregister(safety_trigger)
This way when your script starts, you set it to automatically delete FILENAME when it ends. Once you're done writing to the file, you tell your script NOT to automatically delete FILENAME when it ends.
You could simply prepare the information for writing first and only perform the saving and such if it makes it through preparation without a hitch.
info_to_write = ""
try:
info_to_write += "something!"
# etc...
if something_went_wrong:
raise Exception
with open("file.txt","w") as f:
f.write(info_to_write)
catch:
print "Nothing written, no file created"

How to append a list to a file on Python using JSON

I'm getting a bit of a trouble here. I have a text file with ["Data1", "Data2", "Data3"], and I want to make that if data1 is not in the file, then append a new list with all three strings, and if data is already there, then just print it. What is broken in this code and why?
filename = "datosdeusuario.txt"
leyendo = open(filename, 'r')
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
P.S.: I am a rookie in Python, and I'm getting confused often. That's why I am not using any dicts (no idea what they are anyway), so I'd like to make that code work in the most simple way.
P.S.2: Also, if that works, my next step would be to make a search engine to return one specific of the three data items in the list. For example, if I want to get the data2 in a list with username "sael", what would I need to do?
It seems that you're reading from the file pointer, NOT from the data in the file as you expected.
So, you first need to read the data in the file:
buffer = leyendo.read()
Then do your check based on buffer, not leyendo:
if user.name in buffer:
Also, you're opening the file two times, that may be kind of expensive. I am not sure if Python got a feature to open the file in both read and write modes.
Assuming that your user.name and your Print functions are working, you need to read the file and close the file.
Try this:
filename = "datosdeusuario.txt"
f = open(filename, 'r')
leyendo = f.read()
f.close()
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
First, you should close the file in both cases, and I think you should close the file before re-opening it for appending.
I think the problem is with the line:
if user.name in leyendo:
which will always return false.
You should read the file and then question it like so:
if user.name in leyendo.read():

Take user input and put it into a file in Python?

I must have skipped a page or two by accident during my PDF Tutorials on Python commands and arguments, because I somehow cannot find a way to take user input and shove it into a file. Don't tell me to try and find solutions online, because I did. None made sense to me.
EDIT: I am using Python 3.1.2, sorry for forgetting
Solution for Python 3.1 and up:
filename = input("filename: ")
with open(filename, "w") as f:
f.write(input())
This asks the user for a filename and opens it for writing. Then everything until the next return is written into that file. The "with... as" statement closes the file automatically.
Solution for Python 2
Use raw_input() to take user input. Open a file using open() and use write() to write into a file.
something like:
fd = open(filename,"w")
input = raw_input("user input")
fd.write(input)
Try Something Like This.
#Getting Where To Save File
where = raw_input('Where Do You Want To Save Your File? ')
#Getting What To Write To File
text = raw_input('What Do You Want To Write To Your File? ')
#Actually Writing It
saveFile = open(where, 'w')
saveFile.write(text)
saveFile.close()
Try this out as this also places your input lines each on a new line.
filename = "temp.txt"
with open(filename, "w") as f:
while True:
try:
f.write(input())
f.write("\n")
except EOFError:
break

Categories

Resources