Avatar of csehz
csehz
Flag for Hungary asked on

Python - writing to a .csv file

Dear Experts,

I have a small Excel file with the data as it the below print screen shows:
Excel file
which are imported by Python through a .csv file by the following code:
import csv

with open(r"C:\Users\ac324485\Downloads\Daily files\File.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    
for x in data_header:
    print(x)
    
for x in data_rows:
    print(x)

Open in new window


Could you please advise which Python syntax could write back data to that Excel file to cell A2 (so to the place of value '10101')?

Thanks in advance,
Python

Avatar of undefined
Last Comment
csehz

8/22/2022 - Mon
Subodh Tiwari (Neeraj)

What are you trying to achieve here by reading the file and writing back to the same file?

BTW you may give this a try...
import pandas as pd

file = r"C:\Users\ac324485\Downloads\Daily files\File.csv"
df = pd.read_csv(file)
print(df)

df.to_csv(file,index= False)

Open in new window

csehz

ASKER
Neeraj thanks I will try, in the meantime confirming that yes, I would like to have this input file in Python and writing back to it also some values (those will come from other application as final target)
csehz

ASKER
Do you have maybe an idea which does not use pandas library, so rather the import csv one?
Your help has saved me hundreds of hours of internet surfing.
fblack61
Subodh Tiwari (Neeraj)

There are multiple libraries you can use to deal with csv files but I find pandas very much practical when dealing with tabular data, it's my personal preference. Actually I don't use Python much so have no idea about csv library and it's methods. You may look into the csv documentation for more info.
ASKER CERTIFIED SOLUTION
pepr

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
csehz

ASKER
@pepr thank you that works great