Save a list to a .txt file and keep them - python

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

Related

How to delete replace string in text file from 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)))

Load new values from another Python script

I have a device which I am controlling in a for loop. I would like to check every iteration if a .txt file has changed. If it has I want to read values and send them to the device. I am checking if file was updated like this:
os.stat("myfile.txt").stat.st_mtime
This is working fine when I manually open file, write values and save file.
I want to change values by another Python script which will be run by another process. In this other script I write values to the .txt file like this:
text_file = open("myfile.txt", 'w')
text_file.write("\n0\n0\n0")
text_file.close()
When I call open(), st_mtime changes and I load nothing because text file is empty. How to deal with this? Are there other approaches besides a text file to set new values by another Python process?
You could try an alternate way to check if the contents have changed, by checking for MD5 checksum for example.
import hashlib
..
my_hex = hashlib.md5(text_file.read()).hexdigest()
You can now monitor my_hex every iteration to check if your file contents have changed.
I used 3 files. I check if 3th files st_mtime has changed. I write new values to a second file, and than open and close 3th file. St_mtime of the 3th file changes so i load values from second file safely. :)

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().)

How to append new rows to .txt file

Hi below is a piece of code from my command line interface on python i am trying to use this to create new users and append them to a .txt file, however whenever i append new data by running the programme it all saves to the rame row and i feel as though i have tried everything to solve this problem.
So please could anyone tell me how to append new data to a new row.
Thanks
That's because you've forgotten to add the new line character: \n.
with open('seano.txt', "a") as file:
file.write(str(user) + "\n")
See methods of file objects.

Python opening a file and turning it into a list

I am trying to open a file and then take that file and turn it into a list I'm kinda lost as to how to get it into a list i know I can open a file with open() I don't want to use the read.line either
Input (build1,200),(build2,267) all in a txt file that needs to be opened
Output
Build1,200
Build2,200
Every time I try to add the info to a list it just adds the first one then it stops .
This will put the each line into separate sub lists in a 2d list:
sav = []
with open("filename", "r") as fileopen:
for line in fileopen:
sav.append(line.split())
I'm assuming you are using a .txt file.
This is basically going to make an sequence named 'tup'. What open() does is open up the file. The two arguments that you pass will be the 'filename' and the what you want to do with the contents of the file. Filename is going to be the entire directory of the file, i.e "C:/User...../file.txt". What 'r' signify is 'read' a file only. tuple() will create a sequence of data from your file which will be immutable (you cannot change it), but you can access the data within it.
tup=tuple(open(file,'r'))

Categories

Resources