How to delete replace string in text file from python? - python

So I have a script that I want to have save the amount of hours you have logged. The data is kept in a .txt file and the data is the only thing in that file. There will always only be one line in the file. I want to read the current number saved in the file, delete the number, then replace it with a new number that I get from the user.
with open("fullHours.txt", "r+") as fullHours:
fullHours.write(str(int(fullHours.read()) + int(new_number)))
This code just appends to the current integer, but I want the original number in the file to be replaced with the new number.

First open the file in "r" mode, read the current data, and close the file.
Then open the file in mode "w", and write the new value.

Move the cursor to the start of the file to remove the old content.
with open("fullHours.txt", "r+") as fullHours:
previous_number = fullHours.read()
fullHours.seek(0)
fullHours.write(str(int(previous_number) + int(new_number)))

Related

Save a list to a .txt file and keep them

I found a way to print the list to a txt file, and it worked for me. Except for one detail,
with open("data.txt", "w") as output:
output.write(str(list))
When I make a different data entry, new data replaces the old data I entered, I want it not to delete the old data and continue recording new data.
using "w" in the open function will rewrite the complete file so use "a" in the open function which will append the file and you will not lose the original text in the file

Strings aren't being written to new file

I have a list of JSON objects stored as a text file, one JSON object per line (total size is 30 GB), and what I'm trying to do is extract elements from those objects and store them in a new list. Here is my code to do that
print("Extracting fingerprints...")
start = time.time()
for jsonObj in open('ctl_records_sample.jsonlines'):
temp_dict = {}
temp_dict = json.loads(jsonObj)
finger = temp_dict['data']['leaf_cert']['fingerprint']
with open("fingerprints.txt", "w") as f:
f.write(finger+"\n")
finger = ""
end = time.time()
print("Fingerprint extraction finished in" + str(end-start) +"s")
Basically, I'm trying to go line-by-line of the original file and write that line's "fingerprint" to the new text file. However, after letting the code run for several seconds, I open up fingerprints.txt and see that only one fingerprint has been written to the file. Any idea what could be happening?
Your code here is the issue:
with open("fingerprints.txt", "w") as f:
f.write(finger+"\n")
The "w" part will truncate file each time it's opened.
You either want to open the file and keep it open throughout your loop, or check that the file exists and if it does open it with "a" to append.
You're opening the file in each loop iteration, in write mode as per your w parameter passed to the open function. Therefore it's being overwritten from the beginning.
You can solve it for example with two different approaches:
You can move your with statement before the for loop and everything will work, since it will be writing sequentially over the same file (using the same descriptor and pointer into the file).
Open the file in append mode each time, what will append your new written content to the end of the file. To do so, replace your w with an a.
When calling open() with the "w" mode, all the file contents will be deleted. From the Python documentation for the open() function:
'w': open for writing, truncating the file first
I think you are looking to use the "a" mode, which appends new contents to the end of the file:
'a': open for writing, appending to the end of the file if it exists
with open("fingerprints.txt", "a", newline="\n") as f:
f.write(finger)
(You can also drop the +"\n" to the f.write() call by passing the newline="\n" argument to open().)

Files in Python 3

I have the following code:
# Read files
file = open("lightning_data.txt",'r')
filelen=len(file.read())
print('file length is', filelen)
file.close()
file = open("lightning_data.txt",'w')
if filelen<3:
file.write('0.90 \n1.68 \n10.752 \n8.54892')
print('written to file')
file.close()
When i run it, i see the following:
file length is 0
written to file
The file has been created and filled with "0.90 \n1.68 \n10.752 \n8.54892"
If i run it again, the output is:
file length is 27
And the file becomes empty! Why?
Solved
The problem is, the command
file = open("lightning_data.txt",'w')
will truncate the file each time you open it. Because of this, when you ran the second time, it truncates the elements inside and you end up with an empty file. You can change this line to
file = open("lightning_data.txt",'a')
and then the contents will not be truncated.
Because the program did what you told it to:
Open the file for writing
Only write to the file (and print about doing so) if its current length (measured in bytes) is less than 3
Close the file either way
When you open the file the second time to write with the mode 'w' you said to overwrite what is in the file and since you don't write anything unless filelen is less than 3 nothing is written therefore you get an empty file. The file mode you are looking for might be 'a'

How do you permanently write to a text file in Python?

I am able to write to a text file using .write(). But after I close() the file and open it again all the written data is gone...? Is there any way that I can permanently save this data on the file?
def writeToFile():
myFile = open("myText.txt","w")
for each in range(8,10):
record = "This is record number {} in the file\n".format(each)
myFile.write(record)
myFile.close()
writeToFile()
So what i meant was that the first time i run this program it appends to the file. After this when i close the program and run it again i want it to write to the file again, but instead it only overrides it, i.e the earlier data is deleted each time i close the program.
The data you wanted to write was indeed permanently written... until you opened again overwriting the previous data.
You have different modes to open the file.
If you know that the file has important data and only want to read it, use this mode.
file = open('./path_to_file', 'r')
If you want to overwrite the data, use this one instead:
file = open('./path_to_file', 'w')
Optionally, you can use this other way instead, and it will close the file for you.
with open('./path_to_file', 'r') as read_file:
for line in read_file:
print line
This will open the file, read it line by line writing it on the screen and closing it for you at the end.
Finally, if you need to open it again and append new content at the end of the file, just use this:
file = open('./path_to_file', 'a')

Python: Putting Charater in front or behind a file

I want to write a couple characters into a file where there is already text inside. What would be the code to add characters to the front of the file and to the back of the text file if I want the text that was initially in the file to remain in the center?
To add some text to the end of your file, simply open it in append mode and then write to it as usual.
open('file.txt', 'a')
If you want to add something to the beginning of the file, and you don't mind loading the contents of the file temporarily into memory.
addedText = 'Hello World!'
with open('file.txt', 'r+') as myFile:
filecontents = myFile.read()
myFile.seek(0,0)
f.write(addedText.rstrip('\r\n') + '\n' + filecontents)
When you want to open a file and keep its content you have to open the file in append mode. Also have a look at:
file.seek (can be used to set the files current position)
There is no function in any knows underlying file systems that allows to insert bytes into a file. You can only :
add bytes (characters) at the end of the file (append mode)
rewrite bytes in place anywhere in the file
truncate a file at current position.
So if you want to add anything not at the end of the file, the common way (that is used by many text editors) is :
rename the old file to a temp name (it is known as a backup copy)
create a new file with the original name and write what you want to it (here the prefix, the original content and the postfix)
(optionaly) delete the backup copy.
That way allows you to recover your file even if bad things occur while writing the new copy : you can at least get the previous copy and restart your edition.

Categories

Resources