Reputation: 73
I have a CSV file that I have successfully removed lines from using the following code:
myfiles = glob.glob('myfile.csv')
for file in myfiles:
lines = open(file).readlines()
open(file, 'w').writelines(lines[27:])
Now what remains in the CSV file is the following:
"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10"
"Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"
"Copy of Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"
What I want to do:
I have been trying to edit the CSV file using the code above to completely delete line 6 but don't know how to add it to the code above and also edit Line 2 and line 4 to remove the last 3 three contents of the line (F8,F9,F10 and 1000,2000,3000 respectively) --> so the CSV should look like the following below:
"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7"
"Football weights", "8", "10", "11", "120", "10", "21", "20"
Thank you in advance if anyone can give me some pointers or tips.
Upvotes: 2
Views: 1126
Reputation: 8557
Use the csv
module to read and rewrite back without the last 3 columns
for file in myfiles:
rows = []
with io.open(file,"r",encoding="utf-8") as f:
reader = csv.reader(f, delimiter=",", quotechar='"')
for row in reader:
rows.append(row[:-3])
with io.open(file,"w",encoding="utf-8") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
Upvotes: 2
Reputation: 900
Here's a simple solution using the csv library.
import csv
# myfiles = ['f1.csv', 'f2.csv'] # this is for my testing
myfiles = glob.glob('myfile.csv')
for file in myfiles:
with open(file, 'r') as csvfile:
lines = list(csv.reader(csvfile, quotechar='"')) # Read input file
with open(file, 'w') as csvfile:
writer = csv.writer(csvfile) # Write to the same file
# Remove the last line (I don't know exactly if you need to)
for line in lines[27: -1]: # Remove -1 to keep the last line
# Removing last three columns
writer.writerow(line[: -3])
Let me know if there's anything else I can help with.
Upvotes: 1
Reputation: 121
You can create a dataframe from the csv file and use drop function to delete the columns and rows in it.
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Remove last 3 columns.
new_df=df.drop(df.iloc[:, -3:], axis = 1)
# Remove last row.
new_df=df.drop(df.iloc[-1,:],axis=1)
Upvotes: 1