为名称存储在csv文件中的多个文本文件运行python脚本

时间:2017-12-13 15:23:59

标签: python

我在文件夹/ Users / Don / Desktop / TextAuto中有文本文件(100.txt,101.txt,102.txt)等。现在我写了一个脚本来从每个文本文件中提取某些信息。现在我需要为所有文件运行此脚本(100.txt,101.txt,102.txt等..)。

我试过这个:input.csv有文本文件名100.txt,101.txt ...

import re
import csv

with open ('input.csv') as csvfile :
     readCSV = csv.reader(csvfile, delimiter=',')
     for row in readCSV :
         text1 = row[0]
         text2 = row[1]
         textopen = open('/Users/Don/Desktop/TextAuto/'+proto)
         print(textopen)

输出:它不是打印textopen的内容,而是给了我“”

我试图这样做的另一种方式是:

import re
import csv

with open ('input.csv') as csvfile :
     readCSV = csv.reader(csvfile, delimiter=',')
     for row in readCSV :
         text1 = row[0]
         print(text1)

输出:100.txt

2 个答案:

答案 0 :(得分:1)

您应该先阅读打开的文件textopen,然后再打印它。例如:

     textopen = open('/Users/Don/Desktop/TextAuto/'+proto)
     print(testopen.readlines())

资源:Methods of File Objects

答案 1 :(得分:0)

用户发布了答案并将其删除,但多亏了他,我完成了这件事。

import re
import csv

files = ['100.txt','101.txt','102.txt']

output1 = csv.writer(open('output1.csv','wb'))

for textfile in files:
with open(textfile) as text:
    readtext = text.read()
    try:

        Stuff you want to do
    output1.writerow([column1,column2,column3])#The indentation is important here to store results for all files.