How do I even start sorting/getting data from a .txt file in Python? - python-3.x

So my task involves finding and printing the player name with the most games, shots etc and his name from a .txt file that looks like this;
Rk|Player|Age|Games|Minutes Played|Field Goals|Field Goal Attempts|3P Field Goals|3P Field Goal Attempts
1|Quincy Acy|24|60|1110|126|278|12|47
2|Jordan Adams|20|24|173|22|51|7|16
...
484|Cody Zeller|22|62|1487|172|373|1|1
485|Tyler Zeller|25|74|1560|300|550|0|0
I was thinking about making empty lists and then filling them with for example "Games" and then pull the max value but I don't understand how to pull out the number of games.

You can use python's csv module.
Your code might look like this.
import csv
with open('games.csv', 'rb') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter='|')
for row in csv_reader:
print "Player name: %s, Rank: %s" % (row['Player'], row['Rk'])
Refer to the documentation for more details.

Related

dynamically change header of a CSV file

I'm trying to write a cmd program to track the updated value of investments and things. I want to save their value in a CSV file using csv library and have a history of their values over time. there are some constant investments like ['Gold','Stock','Bit-coin'] and I have added them as default header in my program like this:
+------------+-------------+------------+
| Date | Stock | Gold | Bit-coin |
+------------+-------------+------------+
But I want my program to have the feature for adding Other categories as the user wants to name it. and add and also edit the header whenever wants to edit it.
Is there any way to dynamically edit header names as new column data is added to the CSV file?
import csv
with open('C:/test/test.csv','r') as csvinput:
with open('C:/test/output.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
all = []
row = next(reader)
row.append('Berry')
all.append(row)
for row in reader:
row.append(row[0])
all.append(row)
writer.writerows(all)
Here you can append a new column to your csv file
new_column = input("Enter a new column name:")
Now with this line you can take user input.
You should be able to complete the code on your own, by the way, when posting a question please post the code you're working with so we can grab it and display what you might be requiring with a solution.

Deleting a particular column/row from a CSV file using python

I want to delete a particular row from a given user input that matches with a column.
Let's say I get an employee ID and delete all it's corresponding values in the row.
Not sure how to approach this problem and other sources suggest using a temporary csv file to copy all values and re-iterate.
Since these are very primitive requirements, I would just do it manually.
Read it line by line - if you want to delete the current line, just don't write it back.
If you want to delete a column, for each line, parse it as csv (using the module csv - do not use .split(',')!) and discard the correct column.
The upside of these solutions is that it's very light on the memory and as fast as it can be runtime-wise.
That's pretty much the way to do it.
Something like:
import shutil
file_path = "test.csv"
# Creates a test file
data = ["Employee ID,Data1,Data2",
"111,Something,Something",
"222,Something,Something",
"333,Something,Something"]
with open(file_path, 'w') as write_file:
for item in data:
write_file.write(item + "\n")
# /Creates a test file
input("Look at the test.csv file if you like, close it, then press enter.")
employee_ID = "222"
with open(file_path) as read_file:
with open("temp_file.csv", 'w') as temp_file:
for line in read_file:
if employee_ID in line:
next(read_file)
temp_file.write(line)
shutil.move("temp_file.csv", file_path)
If you have other data that may match the employee ID, then you'll have to parse the line and check the employee ID column specifically.

Writing each sublist in a list of lists to a separate CSV

I have a list of lists containing a varying number of strings in each sublist:
tq_list = [['The mysterious diary records the voice.', 'Italy is my favorite country', 'I am happy to take your donation', 'Any amount will be greatly appreciated.'], ['I am counting my calories, yet I really want dessert.', 'Cats are good pets, for they are clean and are not noisy.'], ['We have a lot of rain in June.']]
I would like to create a new CSV file for each sublist. All I have so far is a way to output each sublist as a row in the same CSV file using the following code:
name_list = ["sublist1","sublist2","sublist3"]
with open("{}.csv".format(*name_list), "w", newline="") as f:
writer = csv.writer(f)
for row in tq_list:
writer.writerow(row)
This creates a single CSV file named 'sublist1.csv'.
I've toyed around with the following code:
name_list = ["sublist1","sublist2","sublist3"]
for row in tq_list:
with open("{}.csv".format(*name_list), "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(row)
Which also only outputs a single CSV file named 'sublist1.csv', but with only the values from the last sublist. I feel like this is a step in the right direction, but obviously not quite there yet.
What the * in "{}.csv".format(*name_list) in your code actually does is this: It unpacks the elements in name_list to be passed into the function (in this case format). That means that format(*name_list) is equivalent to format("sublist1", "sublist2", "sublist3"). Since there is only one {} in your string, all arguments to format except "sublist1" are essentially discarded.
You might want to do something like this:
for index, row in enumerate(tq_list):
with open("{}.csv".format(name_list[index]), "w", newline="") as f:
...
enumerate returns a counting index along with each element that it iterates over so that you can keep track of how many elements there have already been. That way you can write into a different file each time. You could also use zip, another handy function that you can look up in the Python documentation.

Merge line in csv file python

I have this in csv file:
Titre,a,b,c,d,e
01,jean,paul,,
01,,,jack,
02,jeanne,jack,,
02,,,jean
and i want :
Titre,a,b,c,d,e
01,jean,paul,jack,
02,jeanne,jack,,jean
can you help me ?
In general, a good approach is to read the csv file and iterate through the rows using Python's CSV module.
CSV will create an iterator that will let you loop through your file like this:
import csv
with open('your filename.csv', 'r') as infile:
reader = csv.reader(infile)
for line in reader:
for value in line:
# Do your thing
You're going to need to construct a new data set that has different properties. The requirements you described:
Ignore any empty cells
Any time you encounter a row that has a new index number, add a new row to your new data set
Any time you encounter a row that has an index number you've seen before, add it to the row that you already created (except for that index number value itself)
I'm not writing that part of the code for you because you need to learn and grow. It's a good task for a beginner.
Once you've constructed that data set, it will look like this:
example_processed_data = [["Titre","a","b","c","d","e"],
["01","jean","paul","jack"],
["02","jeanne","jack","","jean"]]
You can then create a CSV writer, and create your outfile by iterating over that data, similarly to how you iterated over the infile:
with open('outfile.csv', 'w') as outfile:
writer = csv.writer(outfile)
for line in example_processed_data:
writer.writerow(line)
print("Done! Wrote", len(example_processed_data), "lines to outfile.csv.")

Reading from CSV, updating a value and then re-writing

I am trying to read from a csv file and then update a field based on a users selection and write the contents (including the amendment) to a new csv file. I have managed everything but my solution only writes the amended line and not the rest of the files contents.
The csv file looks like:
1001, item1, 0.5, 10
1002, item2, 1.5, 20
Here is an example of my attempt:
run="yes"
while run=="yes":
id=input("Enter the id of the product you want to order: ")
amount=input("Enter the quantity: ")
reader = csv.reader(open('items.csv', 'r'))
writer = csv.writer(open('updatedstock.csv','w'))
for row in reader:
if id==row[0]:
name=row[1]
price=row[2]
stock=row[3]
newstock=int(stock)-int(amount)
writer.writerow([id, name, price, newstock])
run=input("Do you want to order another item? yes/no ")
You are currently only writing to the new file if you match the id based on the condition:
if id==row[0]:
Change it to always write the row:
run="yes"
while run=="yes":
id=input("Enter the id of the product you want to order: ")
amount=input("Enter the quantity: ")
reader = csv.reader(open('items.csv', 'r'))
writer = csv.writer(open('updatedstock.csv','w'))
for row in reader:
if id==row[0]:
name=row[1]
price=row[2]
stock=row[3]
newstock=int(stock)-int(amount)
writer.writerow([id, name, price, newstock])
else:
writer.writerow(row)
run=input("Do you want to order another item? yes/no ")
If you plan to replace many values, however, this can be very inefficient as the csv will be read in for each change. It would be better to read in all values that you want to change and then go through the csv, modifying the entries desired.
Even better would be to use some other data structure like SQLite that performs better with finds and writes. Of course, this would not be as easily human-readable format as it sits in the filesystem. You can easily output the sqlite database to a .csv if needed: Export from sqlite to csv using shell script.

Resources