0

I have text files(100.txt,101.txt,102.txt) etc in a folder /Users/Don/Desktop/TextAuto. Now i wrote a script to extract certain info from each text file. Now i need to run this script for all the files ( 100.txt,101.txt,102.txt etc..).

I tried this : input.csv has text file names 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)

Output : Instead of printing the content of textopen, it gave me ""

Another way i tried to do this is :

import re
import csv

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

Output : 100.txt

4
  • 1
    use the code blocks. Commented Dec 13, 2017 at 15:26
  • 4
    Where is proto and what does it contain? Commented Dec 13, 2017 at 15:30
  • Ok, still not sure what the problem is. Commented Dec 13, 2017 at 15:33
  • Correction it is not proto , the line is actually textopen = open('/Users/Don/Desktop/TextAuto/'+text1) Commented Dec 13, 2017 at 15:43

2 Answers 2

1

You should read the open file textopen before you can print it. For example:

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

resource: Methods of File Objects

Sign up to request clarification or add additional context in comments.

2 Comments

Well it is reading all the files together at once but instead i'm trying to make it read one file at a time, extract the data needed store in an output file. So my output file should have multiple rows where 1st row will have extracted data from 100.txt, 2nd row will have extracted data from 101.txt so on..
Try print(open('/Users/Don/Desktop/TextAuto/100.txt').readlines()) and see if it prints 100.txt file content.
0

A user posted the answer and deleted it, but thanks to him i got this done.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.