简体   繁体   中英

reading a specific line from one file using a value from another

I have two files. One file contains lines of numbers. The other file contains lines of text. I want to look up specific lines of text from the list of numbers. Currently my code looks like this.

a_file = open("numbers.txt")
b_file = open("keywords.txt")

for position, line in enumerate(b_file):
    lines_to_read = [a_file]
    if position in lines_to_read:
        print(line)

The values in numbers look like this..

26
13
122
234
41

The values in keywords looks like (example)

this is an apple
this is a pear
this is a banana 
this is a pineapple
...
...
...

I can manually write out the values like this

lines_to_read = [26,13,122,234,41]

but that defeats the point of using a_file to look up the values in b_file. I have tried using strings and other variables but nothing seems to work.

[a_file] is a list with one single element which is a_file . What you want is a list containing the lines which you can get with a_file.readlines() or list(read_lines) . But you do not want the text value of lines but their integer value, and you want to search often the container meaning that a set would be better. At the end, I would write:

lines_to_read = set(int(line) for line in a_file)

This is now fine:

for position, line in enumerate(b_file):
    if position in lines_to_read:
        print(line)

You need to read the contents of the a_file to get the numbers out.

Something like this should work:

lines_to_read = [int(num.strip()) for num in a_file.readlines()]

This will give you a list of the numbers in the file - assuming each line contains a single line number to lookup.

Also, you wouldn't need to put this inside the loop. It should go outside the loop - ie before it -- these numbers are fixed once read in from the file, so there's no need to process them again in each iteration.

I would just do this...

a_file = open("numbers.txt")
b_file = open("keywords.txt")

keywords_file = b_file.readlines()
for x in a_file:
  print(keywords_file[int(x)-1])

This reads all lines of the keywords file to get the data as a list, then iterate through your numbers file to get the line numbers, and use those line numbers as the index of the array

socal_nerdtastic helped me find this solution. Thanks so much!

# first, read the numbers file into a list of numbers
with open("numbers.txt") as f:
    lines_to_read = [int(line) for line in f]

# next, read the keywords file into a list of lines
with open("keywords.txt") as f:
    keyword_lines = f.read().splitlines()

# last, use one to print the other
for num in lines_to_read:
    print(keyword_lines[num])

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