This question already has answers here:
Understanding the Python 'with' statement
(5 answers)
Closed 4 years ago.
I am using python 2.x and I am going through company code, I found code that looks like:
filename = open('text.json', 'r')
# doSomething()
filename.close()
I am used to reading a file like so:
with open('text.json', 'r') as filename
# doSomething()
Can anyone explain what the difference is?
The second one is usually used with a context manager, so you can do
with open('text.json', 'r') as filename:
#your code
And you can access the file using the filename alias.
The benefit of that is that the context manager closes the file for you.
If you do manually as your first example you would need to manually call filename.close() after you used it to avoid file locking
When you open a file in python, you have to remember to close it when you're done.
So with your 1st line:
filename = open('text.json', 'r')
You'll need to remember to close the file.
The second version you have is typically used like this:
with open('text.json', 'r') as filename:
#block of code
This will automatically close the file after the block of code is run.
The other difference is the way you're naming the file object as "filename". You end up with the same object in both, just naming it in two different ways.
Related
Can something wrong happen with the following implementation?
def ReadFromFile(file_name):
return [line for line in open(file_name)]
def AppendToFile(new_line, file_name):
open(file_name, 'a').write(new_line)
I am not explicitly calling close() method after reading / writing to the file. My understanding is that semantically the program has to behave as if the file is always closed at the end of each function.
Can the following use of these functions give unexpected results, e.g.
original_lines = ReadFromFile("file.txt")
for line in original_lines:
AppendToFile(line, "file.txt")
modified_lines = ReadFromFile("file.txt")
I would expect e.g. len(modified_lines) == len(original_lines) * 2. Can that ever not be the case?
When we write onto a file using any of the write functions. Python holds everything to write in the file in a buffer and pushes it onto the actual file on the storage device either at the end of the python file or if it encounters a close() function.
Also if we opened another file with same file object then the first file will be closed by python for example:
file_object1 = open(file1,'r')
file_object1 = open(file2, 'r')
Here in this scenario also file1 will be automatically closed
So if the file terminates in between then the data is not stored in the file. So I would suggest two options:
use with because as soon as you get out of the block or encounter any exception it closes the file,
with open(filename , file_mode) as file_object:
do the file manipulations........
or you can use the flush() function if you want to force python to write contents of buffer onto storage without closing the file.
file_object.flush()
For Reference: https://lerner.co.il/2015/01/18/dont-use-python-close-files-answer-depends/
This question already has answers here:
How do I append to a file?
(13 answers)
Closed 5 years ago.
I have a function which prints messages. then I want to save this messages into a file. But when I use .write(function parameter) it only write last message inside my file
writing_in_log = True
def print_and_log(message):
if write_in_log is True:
logFile = open("log", "w+")
logFile.write(message)
logFile.close()
I suppose you are not using the 'a' parameter when opening the file:
with open('file.txt', 'a') as file:
file.write('function parameter')
You probably open the file for each writing with open(yourfile, 'w') which will erase any content from the file before you write to it. If you want to append to your file, use open(yourfile, 'a').
In case this is not the error we need more information about what you are doing, i.e. the relevant parts of the code.
This question already has answers here:
How does using the try statement avoid a race condition?
(3 answers)
Closed 8 years ago.
I would like to know how I could check to see if a file exist based on user input and if it does not, then i would like to create one.
so I would have something like:
file_name = input('what is the file name? ')
then I would like to check to see if file name exist.
If file name does exist, open file to write or read, if file name does not exist, create the file based on user input.
I know the very basic about files but not how to use user input to check or create a file.
if the file is not a file :(return False)
import os.path
if not os.path.isFile(file_name):
print("The File s% it's not created "%file_name)
os.touch(file_name)
print("The file s% has been Created ..."%file_name)
And you can write a simple code based on (try,Except):
try:
my_file = open(file_name)
except IOError:
os.touch(file_name)
To do exactly what you asked:
You're going to want to look at the os.path.isfile() function, and then the open() function (passing your variable as the argument).
However, as noted by #LukasGraf, this is generally considered less than ideal because it introduces a race condition if something else were you create the file in the time between when you check to see if it exists and when you go to open it.
Instead, the usual preferred method is to just try and open it, and catch the exception that's generated if you can't:
try:
my_file = open(file_name)
except IOError:
# file couldn't be opened, perhaps you need to create it
This question already has answers here:
How to print a file to stdout?
(11 answers)
Closed 9 years ago.
I'm trying to get Python to print the contents of a file:
log = open("/path/to/my/file.txt", "r")
print str(log)
Gives me the output:
<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390>
Instead of printing the file. The file just has one short string of text in it, and when I do the opposite (writing the user_input from my Python script to that same file) it works properly.
edit: I see what Python thinks I'm asking it, I'm just wondering what the command to print something from inside a file is.
It is better to handle this with "with" to close the descriptor automatically for you. This will work with both 2.7 and python 3.
with open('/path/to/my/file.txt', 'r') as f:
print(f.read())
open gives you an iterator that doesn't automatically load the whole file at once. It iterates by line so you can write a loop like so:
for line in log:
print(line)
If all you want to do is print the contents of the file to screen, you can use print(log.read())
open() will actually open a file object for you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()
log = open("/path/to/my/file.txt", "r").read()
print log
That will print out the contents of the file.
file_o=open("/path/to/my/file.txt") //creates an object file_o to access the file
content=file_o.read() //file is read using the created object
print(content) //print-out the contents of file
file_o.close()
I am just beginning with python with lpthw and had a specific question for closing a file.
I can open a file with:
input = open(from_file)
indata = input.read()
#Do something
indata.close()
However, if I try to simplify the code into a single line:
indata = open(from_file).read()
How do I close the file I opened, or is it already automatically closed?
Thanks in advance for the help!
You simply have to use more than one line; however, a more pythonic way to do it would be:
with open(path_to_file, 'r') as f:
contents = f.read()
Note that with what you are doing before, you could miss closing the file if an exception was thrown. The 'with' statement here will cause it be closed even if an exception is propagated out of the 'with' block.
Files are automatically closed when the relevant variable is no longer referenced. It is taken care of by Python garbage collection.
In this case, the call to open() creates a File object, of which the read() method is run. After the method is executed, no reference to it exists and it is closed (at least by the end of script execution).
Although this works, it is not good practice. It is always better to explicitly close a file, or (even better) to follow the with suggestion of the other answer.