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.
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')
myFile = open('high scores.py', 'w')
if player1_total > player2_total :
myFile.write(player1_total)
else :
myFile.write(player2_total)
myFile.close
The file write method only expects strings (or bytestrings, if the file is open in binary mode). The max function can save you a conditional, too. Try something like:
with open('high_scores.py', 'w') as myFile:
myFile.write(str(max(player1_total, player2_total)))
You would then be able to read this back with
with open('high_scores.py') as f:
high_score = int(f.read())
Note that the use of the with statements ensures that files are always correctly closed no matter what the outcome of the with block.
Personally, since the file isn't a Python program file I'd use a different extension in its name. For storing a larger set of values consider using the shelve module.
myFile = open('high scores.py', 'w')
if player1_total > player2_total :
myFile.write(str(player1_total))
else :
myFile.write(str(player2_total))
myFile.close()
The issue is that you need to cast the integer to string before writing. easiest way is str(player2_total)
Also close the file once done documentation
When you’re done with a file, call f.close() to close it and free up
any system resources taken up by the open file.
But a concise way to write it is give in this answer.
More info on using the context manager with open(): can be found in PEP-0343 & read up on this blog post as well
cast your values to strings before writing to file:
myFile.write(str(player1_total))
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 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.
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.)