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

2024-06-06 05:07:07 发布

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

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

我试过这个:输入.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


Tags: csvcsvfileimporttxt脚本openusersrow
2条回答

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

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

资源:Methods of File Objects

一个用户发布了答案并将其删除,但多亏了他,我才完成了这项工作。你知道吗

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.

相关问题 更多 >