简体   繁体   中英

How to convert csv to txt file using python?

I want to read a csv file and add the details to txt file only if certain condition is satisfied.

Please find the csv below:

ID,Domain,Reputation_Score,
1,somedomain.domain,50
2,anotherdomain.domain,20

I want to only capture the domain with reputation score more than 30. So the domain with ID "1" should be copied in the txt file (Only domain name is required, nothing else).

Please help.

Regards, Mitesh Agrawal

Pandas might be overkill, but it would be a quick way to filter on any value.

import pandas as pd
df = pd.read_csv('test.csv', index_col="ID")
df = df[df["Reputation_Score"] > 30]
df["Domain"].to_csv("out.txt", header=False, index=False)

Output is:

somedomain.domain

You can use Python's CSV library to do this, for example:

import csv

with open('input.csv', newline='') as f_input, open('output.txt', 'w') as f_output:
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        if int(row[2]) > 30:
            f_output.write(f"{row[1]}\n")

This would give you output.txt as:

somedomain.domain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM