Save Results to CSV File with Python

Save results to csv file with Python

Use csv.writer:

import csv

with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))

import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1

writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
if counter[row[0]] >= 4:
writer.writerow(row)

saving results in csv file

df1 = pd.read_csv('aaa.csv')
df2 = pd.read_csv('bbb.csv', header=None)
keepRow = df2[0].values

# Get rows that have on of the keepRow values in column 0
df3 = df1.loc[df1["firstColumn"].isin(keepRow)]

# drop the keepRow column
df3= df3.drop("firstColumn", axis=1)

#write to csv
df3.to_csv("ok.csv", index=False)

How to output my main() function as a CSV file

Return df from your main function, instead of print(df).
You can also use to_csv function on dataframes.

def main()
...
return df

if __name__ == '__main__':
df = main()
df.to_csv(f'{today}HPD.csv', index=False)

Exporting Python Output into CSV or Text File (Beginner)

You can use the python csv module.

Example:

import csv
import random

data = [random.randint(1, 10) for _ in range(10)]

with open('data.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(data)

data.csv

9,3,7,4,1,3,7,8,1,3


Related Topics



Leave a reply



Submit