读取文本文件并将其内容与多个CSV文件进行比较

2024-09-21 03:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

python脚本应该是这样的work:- 它将检查文件夹中所有csv文件中“words.txt”的内容,并将结果从开始提取到与“words.txt”逐行内容完全匹配的位置

Here is the file structure and the code它适用于两个CSV文件

# Tested on Python 2.7 import csv from itertools import chain with open("words.txt", "rb") as keywords, open('csv1.csv', 'rb') as g, open('csv2.csv', 'rb') as f, open('csv1_modify.csv', 'wb') as myfile1, open('csv2_modify.csv', 'wb') as myfile2: # Step1: Read contents of keywords.tex in variables ky = list(keywords.readlines()) ky1, ky2 = ky[0], ky[1] # Step2: Read and process folding umbrella-sort-highest.csv reader = csv.reader(g) umbrella_list = list(reader) list1 = filter(lambda e: e[0] in ky1, umbrella_list) list2 = list(chain(*list1)) # or better: (available since Python 2.6) # print list(chain.from_iterable(list1)) ind_prt1 = umbrella_list.index(list2) +1 mylist1 = umbrella_list[:ind_prt1] for r in mylist1: wr = csv.writer(myfile1, quoting=csv.QUOTE_ALL) wr.writerow(r) # Step3: Read and process lego minecraft-sort-highest.csv reader = csv.reader(f) minecraft_list = list(reader) list3 = filter(lambda e: e[0] in ky2, minecraft_list) list4 = list(chain(*list3)) # or better: (available since Python 2.6) # print list(chain.from_iterable(list4)) ind_prt2 = minecraft_list.index(list4) +1 mylist2 = minecraft_list[:ind_prt2] for r in mylist2: wr = csv.writer(myfile2, quoting=csv.QUOTE_ALL) wr.writerow(r) print "Task completed, check your working directory."

问题:现在的问题是如何让脚本动态地处理目录中多个CSV文件中“words.txt”的多个关键字内容

它不应该局限于特定数量的关键字或文件,但它应该动态响应任意数量的关键字和文件See what is in my mind

就是这样


Tags: 文件csvintxt内容chainasopen

热门问题