简体   繁体   中英

Extracting the data from the same position over multiple lines in a string

Fairly simple question but I can't figure out where i'm going wrong. I have a text file which I have split into multiple lines. I want to print a certain location from each line, characters 14 to 20 but when I run the below code it prints a blank set of a characters.

with open('filetxt', 'r') as file:
    data = file.read().rstrip()

for line in data:
    print(line[14:20])

If you want to read the file line by line, try:

with open('filetxt', 'r') as file:
    for line in file:
        print(line[14:20])

I think you're using the wrong read() method. read() reads the whole file at once you might want to use readlines() which returns a list of the read lines. Ie:

with open('filetxt', 'r') as file:
  lines = file.readlines()

  for line in lines:
    print(line[14:20])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM