Append onto bottom of .txt file - python

i have a script which takes and records payments. I have created a .txt file to hold transaction information and the code looks like:
payment_file = open('Payments.txt', 'w')
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close()
As an example when i open the txt it will appear as
Card no: XXXX-XXXX-XXXX-1234 | Amount: £15.00
However once one payment is finished the script loops back to the start allowing for another payment to be made but once the next payment is made and you open the .txt the old payment just gets replaced by the most recent one, how would you make sure the payments just get appended underneath eachother

You need to change this :
payment_file = open('Payments.txt', 'a') # ----------> Here a means appending and not overwriting the existing content.
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close()

You need to use append. Append adds data to the end of files. Write writes over the whole file. Please see the following Python documentation for reading and writing to files: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

Related

Editing of txt files not saving when I concatenate them

I am fairly new to programming, so bear with me!
We have a task at school which we are made to clean up three text files ("Balance1", "Saving", and "Withdrawal") and append them together into a new file. These files are just names and sums of money listed downwards, but some of it is jumbled. This is my code for the first file Balance1:
with open('Balance1.txt', 'r+') as f:
f_contents = f.readlines()
# Then I start cleaning up the lines. Here I edit Anna's savings to an integer.
f_contents[8] = "Anna, 600000"
# Here I delete the blank lines and edit in the 50000 to Philip.
del f_contents[3]
del f_contents[3]
In the original text file Anna's savings is written like this: "Anna, six hundred thousand" and we have to make it look clean, so its rather "NAME, SUM (as integer). When I print this as a list it looks good, but after I have done this with all three files I try to append them together in a file called "Balance.txt" like this:
filenames = ["Balance1.txt", "Saving.txt", "Withdrawal.txt"]
with open("Balance.txt", "a") as outfile:
for filename in filenames:
with open(filename) as infile:
contents = infile.read()
outfile.write(contents)
When I check the new text file "Balance" it has appended them together, but just as they were in the beginning and not with my edits. So it is not "cleaned up". Can anyone help me understand why this happens, and what I have to do so it appends the edited and clean versions?
In the first part, where you do the "editing" of Balance.txt` file, this is what happens:
You open the file in read mode
You load the data into memory
You edit the in memory data
And voila.
You never persisted the changes to any file on the disk. So when in the second part you read the content of all the files, you will read the data that was originally there.
So if you want to concatenate the edited data, you have 2 choices:
Pre-process the data by creating 3 final correct files (editing Balance1.txt and persisting it to another file, say Balance1_fixed.txt) and then in the second part, concatenate: ["Balance1_fixed.txt", "Saving.txt", "Withdrawal.txt"]. Total of 4 data file openings, more IO.
Use only the second loop you have, and correct the contents before writing it to the outfile. You can use readlines() like you did first, edit the specific line and then use writelines(). Total of 3 data file openings, less IO than previous option

Config.json number not counting as a number

I'm coding a program for Hypixel SkyBlock Minecraft that tells me the price of items that can be sold for a higher price.
The program is done but I'm running into a issue. I have made a config.json file and it contains information like discord webhook, lowest price, and to notify the user if a item is found. I'm having problems with the lowest price function, basically when I set the lowest price to 1 in the config, the program doesn't work and gets a traceback.
The traceback doesn't matter because I know the issue. When I put the number into config it doesn't work but when i set lowestprice = 1 in program manually it works like when I put the number into config the program thinks maybe the number is a text or something. Here's the config code
with open("config.json", "r") as f:
data = json.load(f)
webhookread = data["webhook"]
notifyread = data["notify"]
lowestpriceread = data["lowestbin"]
WEBHOOK = webhookread
LOWEST_PRICE = lowestpriceread - THE ISSUE
NOTIFY = notifyread
Is there a way I could make the config file put the number as a real number not a text or any of that, so I can still use the config for numbers?
Are the numbers in the json file stored as strings or as numbers? if the json looks like this:
{
"lowestbin" : "123.45"
}
then the price is saved as string and will need to cast to a float type. This is simple to do:
lowestpriceread = float(data["lowestbin"])
Note: this code will thrown an exception if the data in the json cannot be converted into a float.

Is there a way for 2 scripts to write to the same file?

I have limited python experience, but determined to learn. I am trying to create a script that would write some data inputs to excel until stopped. It is very straightforward when a single person is using it but the problem is that 2 people will be using it at once.
I am thinking about making it simple and just having 2 exact same scripts running at the same time, but the problem comes in when the file is going to be saved. If I have two files being saved with the same name, one is going to overwrite the other and the data will be lost. Is there a way to have the scripts create files with different names without having to manually change the code? (This would eventually be scaled to up to 20 computers running it)
The loop looks like:
import xlwt
from xlwt import Workbook
wb = Workbook()
s1 = wb.add_sheet('Sheet 1')
data = []
while user != '0':
user = input('Scan ID Badge: ')
data.append(user)
order = input('Scan order: ')
data.append(order)
item = input('Scan item barcode: ')
data.append(item)
for i in range(len(data)):
s1.write(row,i,data[i])
wb.save('OrderData.xls')
data = []
row += 1
If you want to use a tabular form of data storage anyways, you could switch to a real database and on interval create an excel-like summary of the db file.
If you know all of the users using this script will be using machines with different network names, you could include the computer name in the XLS name:
import platform
filename = 'AssociateEfficiencyTemp-' + platform.node() + '.xls'
# ...
wb.save(filename)
(You can also use getpass.getuser() to (try and) get the username of the user running the script.)
You can then write another script that reads all of the separate files (glob.glob('AssociateEfficiencyTemp-*.xls') etc.) and combines them.
(I would suggest using another format than .xls for the intermediary files though, such as plain text files of JSON lines.)

How to connect my Python 3 code to the CSV files on my laptop?

I am working on a homework problem and I thought I had it, but my program cannot read the files on my laptop so I get an error when I attempt to run my code. The files are all titled ssa(year).txt
The code I have tried seems to be all correct except for the portion that handles the files. None of my CSCI tutors could help.
import csv
my_list=[]
with open("ssa2017.txt", 'r') as f:
reader = csv.reader(f,delimiter='\t')
fields = next(reader)
for row in reader:
row=[row[0],row[1],int(row[2]),row[3].lower().title(),int(row[4])]
my_list.append(row)
def func1():
state=input('Enter the State Abbreviation or just press enter: ')
if state=='':
state="US"
year=input('Enter the years you want to search: ').split()
y1=int(year[0])
y2=int(year[1])
my_dict={}
for row in my_list:
if row[2]>=y1 and row[2]<=y2 and state==row[0]:
if row[3] not in my_dict.keys():
my_dict[row[3]]=row[4]
else:
my_dict[row[3]]=my_dict[row[3]]+row[4]
sorted_by_value = sorted(my_dict.items(), key=lambda kv: kv[1],reverse=True)
print('Top 5 names')
for i,key in enumerate(sorted_by_value):
print(str(i+1)+': '+key[0]+' ('+str(key[1])+')')
def func2():
name=input('Enter the name: ').lower().title()
year=int(input('Enter the years: '))
state=input('Enter the State Abbreviation or just press enter: ')
my_dict={}
for row in my_list:
if year==row[2] and state==row[0]:
if row[3] not in my_dict.keys():
my_dict[row[3]]=row[4]
else:
my_dict[row[3]]=my_dict[row[3]]+row[4]
sorted_by_value = sorted(my_dict.items(), key=lambda kv: kv[1],reverse=True)
for i,key in enumerate(sorted_by_value):
if key[0]==name:
print('\nThe name',name,'was in position',i+1)
while True:
print('\n1) Search by Year/Location\n2) Search by name\n3) Quit')
choice=input('Select the option: ')
if choice=='1':
func1()
elif choice=='2':
func2()
elif choice=='3':
break
else:
print('Please select the valid option.')
I AM NOT TRYING TO GET YOU DO DO MY HW, BUT THIS IS WHAT IS EXPECTED.
home / study / engineering / computer science / computer science questions and answers / in python 3 the u.s. social security administration publishes lists of baby names for every ...
Question: IN PYTHON 3 The U.S. Social Security Administration publishes lists of baby names for every year ...
IN PYTHON 3
The U.S. Social Security Administration publishes lists of baby names for every year since 1880.
The data for each year is stored in a separate file. The files all have the format
Name,Sex(M/F),Number
The Number is the number of children given the name in that year. These files are edited so that they are shorter and only include names with >= 100 entries for that year.
You are to create a program to provide information from these files:
-For each year of data needed, your program must read the file 'ssaxxx.txt' where xxxx is the year needed.
-The data file format is consistent and for this assignment you DO NOT have to check for errors in the data files
-You do no need to check each user input (choice and years) for errors and handle those without crashing
-The program must include a function called name(). This function takes two arguments. The first is the year as an integer and the second is the type of name to search for: 'M' for male, 'F' for female, and 'E' for everyone. The function must return both the most popular name for that year and the number of times the name was given.
To develop/test the program, you need to get the data files from 1980 to 2018, These can be found in the files section below in a zip file. You DO NOT need to upload the data files to Zybooks (only upload your program), they are only for you development purposes.
The program must offer the following options
-The first option will scan the files and print the most popular name for each year (regardless if it is male or female) along with the number of that name given for each year
-The second option will look at all all the years and find the most popular name overall and the overall total for that name
-The third option is like the first one, except it will print the most popular male name for each year along with the number of the name given for each year
-The fourth option will print the most popular female name for each year along with the total number of that name given for that year
After each option (other than quit), ask for a starting and ending year.
This is what the SSA file looks like
Here is my error
HERE IS A PORTION OF THE FILE:
Aiden,M,11259
Cielo,F,143
Zephaniah,M,136
Allyson,F,634
Jessa,F,307
Omar,M,1639
Micaela,F,239
Annalee,F,287
Nolan,M,5375
Ronnie,M,238
Nico,M,747
Milani,F,536
Kaila,F,133
Zakari,M,106
Emilie,F,248
Rex,M,428
Luciana,F,782
Karla,F,552
Misael,M,243
Zendaya,F,258
Rayna,F,391
Krystal,F,200
Nathaly,F,213
Brielle,F,2880
Daenerys,F,110
Galilea,F,527
Aspyn,F,178
Giovanni,M,2783
My guess is that your ssa2017.txt is not in the same folder with the script you are executing.
You can investigate the absolute path which Python looking for the ssa2017.txt by adding these lines at the top of your script:
import os
full_path = os.path.abspath('ssa2017.txt')
print(full_path)
If the full_path variable here is not the same as your path to ssa2017.txt, it's the reason why your Python script can not access the text file.
The error you mentions states that it cannot find the file ssa2017.txt. By default, python tries to look for a file you are trying to open in the same folder you are trying to run the script in. So you need to provide the whole path of the file.
So you can either do
with open("<folder_with_text_files>/ssa2017.txt", 'r') as f:
#do stuff
Or if you have all your files in the same folder, you can use os.listdir to list them and then open it
import os
folder_with_files = '/Users/devesingh/Downloads'
#List all files in folder
for file in os.listdir(folder_with_files):
#If the file has ssa in it
if 'csv' in file:
#Get the full file path and use it to open
full_file_path = os.path.join(folder_with_files, file)
with open(full_file_path, 'r') as f:
#do stuff

How to make an input function to find something in a certain row in a CSV file using Tkinter

Okay so I'm making a GUI to look for a specific number in a CSV file basically
ID: Name: Address: Email:
1023 John 123 Normal St John123#hotmail.com
So basically I want the person using the GUI to type in the ID and the GUI just goes through the CSV file and prints the whole row
Also I'm a novice coder so please don't judge me if I keep asking what a certain element is or what does this thing do
Thank you
First Off CSV stands for Comma Separated Values so naturally,we would expect your columns to be comma-separated not space -separated,I tried to adapt the code with your data but in the future,do separate your .csv data with commas
You could simply use readlines to read the contents of a .csv file.The logic you are looking for will be something like:
idx = 2710
with open('my.csv','r') as f:
data = f.readlines()
for d in data:
if d.find(str(idx)) != -1:
print(d)
break
i have already answered a similar question on the tkinter gui here,which applies to the same case as yours,all you have to do is paste the above logic into the on_click function and replace print(d) with text.insert(INSERT, d)
I would recommend reading about tkinter,also just a side dish pandas has some nice functions for working with .csv files,worth reading about

Categories

Resources