Artificial Intelligence Artificial Intelligence - 1 year ago 83
Python Question

Trying to read a file and loop through at the same time

I'm pretty new to this so please move this topic if it's in the wrong place or something else.

Problem: (Quick note: This is all in Python) I am trying to go through these 100 or so files, each with the same number of columns, and take certain columns of the input (the same ones for each file) and write them in a new file. However, these 100 files don't necessarily all have the same number of rows. In the code below, filec is in a loop and continues altering throughout the 100 files. I am trying to get these certain columns that I want by looking at the number of rows in each txt file and looping that many times then taking the numbers I want.

filec = open(string,'r').read().split(',')
x = len(filec.readlines())

I realize the issue is that filec has become a list after using the split function and was originally a string when I used .read(). How would one go about finding the number of lines, so I can loop through the number of rows and get the positions in each row that I want?

Thank you!

Answer Source

You could do it like this:

filec = open (filename, 'r')
lines = filec.readlines ()

for line in lines:
    words = line.split(',')
    # Your code here

Excuse me if there are any errors, I'm doing this on mobile.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download