KHajnalka
KHajnalka

Reputation: 11

Read a file line by line but only some characters within each line

I have a text file and I would like to get the string from the 300th character to the 500th character (or column in the text file) within each line and put the string into a list.

I started my code with this but I don't know how to modify the file reading with specifying the ch.

with open("filename") as f:
for line in f:  
   for ch in line: 

Upvotes: 0

Views: 1136

Answers (2)

Aneel
Aneel

Reputation: 1433

You can use the subscript slicing notation on python strings:

lines = []
with open("filename") as f:
    for line in f:
        lines.append(line[300:500])

Or

with open("filename") as f:
    lines = [l[300:500] for l in f]

Upvotes: 2

rassar
rassar

Reputation: 5660

Try:

with open("filename") as f:
    for line in f:  
       chs = line[299:500]

This should slice it and return the characters from 300-500. From there, you could just do list.append to put it into a list, or whatever you need to do.

Upvotes: 3

Related Questions