简体   繁体   English

如何使用Python脚本从CSV文件过滤

[英]How to Filter from CSV file using Python Script

I have abx.csv file having three columns. 我有abx.csv文件有三列。 I would like to filter the data which is having Application as Central and write it in same .csv file 我想过滤具有Application as Central的数据并将其写入相同的.csv文件中

User ID   Name        Application  

001       Ajohns      ABI
002       Fjerry      Central
900       Xknight     RFC
300       JollK       QDI
078       Demik       Central

I need to write User ID,Name,Apllication in three column in same .csv file (modifying the existing file) 我需要在同一个.csv文件中的三列中写入User ID,Name,Apllication (修改现有文件)

import csv
reader = csv.reader(open(r"abx.csv"),delimiter=' ')
filtered = filter(lambda p: 'Central' == p[2], reader)
csv.writer(open(r"abx.csv",'w'),delimiter=' ').writerows(filtered)

You should use different output filename. 您应该使用不同的输出文件名。 Even if you want the name to be the same, you should use some temporary name and finally rename file. 即使您希望名称相同,也应使用一些临时名称,最后重命名文件。 Otherwise you have to read file to memory at first 否则你必须先将文件读入内存

import csv
with open('infile','r'), open ('outfile','w') as fin, fout:
    writer = csv.writer(fout, delimiter=' ')            
    for row in csv.reader(fin, delimiter=' '):
        if row[2] == 'Central':
             writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Python 脚本从巨大的 CSV 文件中过滤特定行 - How to Filter specific rows from a huge CSV file using Python Script 如何使用python从CSV文件中过滤两个日期之间的行并重定向到另一个文件? - How to filter rows between two dates from CSV file using python and redirect to another file? 如何使用python基于阈值数值从csv文件过滤行 - How to filter rows from a csv file based on threshold numerical values using python 在另一个 python 脚本中使用 output.csv 文件 - Using output .csv file from one python script in another 使用python脚本将文件从.xls转换为.csv时,如何使数字不显示为指数? - How to get numbers to NOT appear as exponentials when converting a file from .xls to .csv using python script? 如何使用 python 从 csv 文件中过滤掉可用数据? - How to filter out useable data from csv files using python? 使用Pandas和Python过滤CSV文件程序 - Filter CSV File Program using Pandas and Python 如何使用 python 将 CSV 文件的每 N 行导入脚本 - How to import every Nth row of CSV file using python into script 如何使用 python 脚本将 xml 文件转换为 csv - how to convert xml file to csv using python script 如何使用来自另一个 .txt 的列表过滤 .csv/.txt 文件 - how to filter a .csv/.txt file using a list from another .txt
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM