I am working on a project and have a great idea.
This is a very simple question and I've done this before, but it doesn't seem to be working.
In my idle, when I type:
f = open('a.txt', 'w')
f.write('hi')
I get an output of 2.
It doesn't make sense to me beyond the fact that hi has a length of two... I want to add 'hi' to my file!!
you just need to use f.close() and the changes will commit
Consider using the context handler when dealing with fileIO. By using the with statement as shown below, the file will automatically close when the codeblock is finished executing.
with open('a.txt', 'w') as f:
f.write('hi')
This saves you from having to remember to close the file when you're done with it.
Related
Here is my code of accessing&editing the file:
def edit_default_settings(self, setting_type, value):
with open("cam_settings.json", "r") as f:
cam_settings = json.load(f)
cam_settings[setting_type] = value
with open("cam_settings.json", 'w') as f:
json.dump(cam_settings, f, indent=4)
I use It in a program that runs for several hours in a day, and once in a ~week I'm noticing, that cam_settings.json file becoming empty (literally empty, the file explorer shows 0 bytes), but can't imagine how that is possible
Would be glad to hear some comments on what could go wrong
I can't see any issues with the code itself, but there can be an issue with the execution environment. Are you running the code in a multi-threaded environment or running multiple instances of the same program at once?
This situation can arise if this code is executed parallelly and multiple threads/processes try to access the file at the same time. Try logging each time the function was executed and if the function was executed successfully. Try exception handlers and error logging.
If this is a problem, using buffers or singleton pattern can solve the issue.
As #Chels said, the file is truncated when it's opened with 'w'. That doesn't explain why it stays that way; I can only imagine that happening if your code crashed. Maybe you need to check logs for code crashes (or change how your code is run so that crash reasons get logged, if they aren't).
But there's a way to make this process safer in case of crashes. Write to a separate file and then replace the old file with the new file, only after the new file is fully written. You can use os.replace() for this. You could do this simply with a differently-named file:
with open(".cam_settings.json.tmp", 'w') as f:
json.dump(cam_settings, f, indent=4)
os.replace(".cam_settings.json.tmp", "cam_settings.json")
Or you could use a temporary file from the tempfile module.
When openning a file with the "w" parameter, everytime you will write to it, the content of the file will be erased. (You will actually replace what's written already).
Not sure if this is what you are looking for, but could be one of the reasons why "cam_settings.json" becomes empty after the call of open("cam_settings.json", 'w')!
In such a case, to append some text, use the "a" parameter, as:
open("cam_settings.json", 'a')
If I run
file = open("BAL.txt","w")
I = '200'
file.write(I)
file.close
from a script, it outputs nothing in the file. (It literally overwrites the file with nothing)
Furthermore, running cat BAL.txt just goes to the next line like nothing is in the file.
But if I run it line by line in a python console it works perfectly fine.
Why does this happen. ( I am a begginner learning python the mistake may be super obvious. I have thrown about 2 hours into trying to figure this out)
Thanks in advance
You aren't closing your file properly. To close it you are missing the () at the end of file.close so it should look like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
This site has the same example and may be of some use to you.
Another way, especially useful when you are appending multiple values into a single file is to use something like with open("BAL.txt","w") as file:. Here is your script rewritten to include this example:
I = '200'
with open("BAL.txt","w") as file:
file.write(I)
This opens our file with the value file and allows us to write values to it. Also note that file.close() is not needed here and when appending text w+ needs to be used.
to write to a file you do this:
file = open("file.txt","w")
file.write("something")
file.close()
when you use file.write() it deletes all of the contents of the file, if you want to write to the end of the file do this:
file = open("file.text","w+")
file.write(file.read()+"something")
file.close()
There are other ways to do this but this one is the most intuitive (not the most efficient), also the other way tends to be buggy so there is no reason to post it because this is reliable.
Firstly, you're missing the parentheses when you're closing the file. Secondly, writing to a file should be done like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
Let me know if you have any questions.
I tried to write to a binary (*.bin) file and I met a problem.
When I use the following code, it does not write anything to the file:
abc = str.encode("sabd")
f=open("sbd.bin",'wb')
f.write(abc)
f.close
However, when I use the following code, it works well:
abc = str.encode("sabd")
with open("sbd.bin",'wb') as f:
f.write(abc)
I use Win + Python3.
Instead of f.close, try f.close() to see if that works any better since close() is a method.
I suggest flushing the data to the file, as you are missing this and would cause the file to not be created or written to. e.g. file.flush() will create the file if not existent and write the data to it.
source: https://www.tutorialspoint.com/python3/file_flush.htm and as suggested by cdlane, close the file with file.close() as you are calling a method not getting a variable or something.
I'm trying to clean up my code a little bit, and I have trouble figuring which of these 2 ways is considered the most pythonic one
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
f = open(os.path.join(dir,str1),'r')
Although the second seems to be cleanest one, I find the declaration of fullPath a bit too much, since it will only be used once.
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
fullPath = os.path.join(dir,str1)
f = open(fullPath,'r')
In general, is it a better thing to avoid calling functions inside of another call, even if it adds a line of code ?
with open('file path', 'a') as f:
data = f.read()
#do something with data
or
f = open(os.path.join(dir,str1),'r')
f.close()
file = open('newfile.txt', 'r')
for line in file:
print line
OR
lines = [line for line in open('filename')]
If file is huge, read() is definitively bad idea, as it loads (without size parameter), whole file into memory.
If your file is huge this will cause latency !
So, i don't recommend read() or readlines()
There are many ways to open files in python which goes to say that there really isn't really a pythonic way of doing it. It all just boils down to which method you see are most connivence, especially in regards to what you're actually trying to do with the file once its open.
Most users use the IDLE GUI "click" to open files because it allows them to view the current file and also make some alterations if there's a need for such.
Others might just rely on the command lines to perform the task, at the cost of not being able to do anything other than opening the file.
Using Command Lines:
% python myfile.py
note that in order for this to work you need to make sure the system is "looking" into the directory where your file is storied. Using the 'cd' is useful to finding you route there.
% python import myfile myfile.title
This method is known as the object.attribute method of opening files. This method is useful when the file you're opening has an operation that you would like to implement.
There are more ways than what's been stated above, be sure to consult the pyDocs for further details.
I would like to write 'yes it does' into a text file I made earlier. when I run my code, it says 'AttributeError: exit'. I was wondering how to remove this error and make it work successfully, thanks for the help.
The code is:
file = ()
def rewrite_test():
open ('testing.txt', 'rb+')
with ('testing.txt'):
print ("yes it does")
rewrite_test()
You can do it like this:
def rewrite_test():
with open('testing.txt', 'w+') as fout:
fout.write('Yes it does.')
Where you had with ('testing.txt'), that would raise an exception because the string 'testing.txt' isn't something that supports the requirements of a with block.
Also you need to open a file for writing not reading, so use 'w' instead of 'r'.
If you don't like using with, you can use the following code:
def rewrite_test() :
f = open('testing.txt', 'w') # You can replace w with a if you want to append
f.write('Yes, it does')
f.close()
rewrite_test()
So it just opens the file, writes to it, and closes it. Also works in Python 2, which doesn't get with. (I am also a Python 2 user, and I don't understand what with does or is.)