简体   繁体   English

从列表中读取Python中读取文本文件的第n行

[英]Reading an nth line of a textfile in python determined from a list

I have a function gen_rand_index that generates a random group of numbers in list format, such as [3,1] or [3,2,1] 我有一个函数gen_rand_index ,它以列表格式(例如[3,1][3,2,1]生成一组随机数字

I also have a textfile that that reads something like this: 我还有一个文本文件,其内容如下:

red $1 红色$ 1

green $5 绿色$ 5

blue $6 蓝色$ 6

How do I write a function so that once python generates this list of numbers, it automatically reads that # line in the text file? 如何编写函数,以便一旦python生成此数字列表,它就会自动读取文本文件中的#行? So if it generated [2,1], instead of printing [2,1] I would get "green $5, red $1" aka the second line in the text file and the first line in the text file? 因此,如果生成了[2,1],而不是打印[2,1],我将得到“绿色$ 5,红色$ 1”,也就是文本文件中的第二行和文本文件中的第一行?

I know that you can do print(line[2]) and commands like that, but this won't work in my case because each time I am getting a different random number of a line that I want to read, it is not a set line I want to read each time. 我知道您可以执行print(line [2])和类似的命令,但这在我的情况下不起作用,因为每次我要读取的行的随机数不同时,它都不是设置我想每次阅读的行。

row = str(result[gen_rand_index]) #result[gen_rand_index] gives me the random list of numbers
file = open("Foodinventory.txt", 'r')
for line in file:
    print(line[row])
file.close()

I have this so far, but I am getting this 到目前为止,我有这个,但是我得到了

error: invalid literal for int() with base 10: '[4, 1]' 错误:int()以10为底的无效文字:“ [4,1]”

I also have gotten 我也得到了

TypeError: string indices must be integers TypeError:字符串索引必须是整数

butI have tried replacing str with int and many things like that but I'm thinking the way I'm just approaching this is wrong. 但是我试图用int和类似的东西替换str,但是我认为我正要解决这个问题的方式是错误的。 Can anyone help me? 谁能帮我? (I have only been coding for a couple days now so I apologize in advance if this question is really basic) (我现在只编码了几天,所以如果这个问题确实很基础,我会提前道歉)

Okay, let us first get some stuff out of the way 好吧,让我们先解决一些问题

Whenever you access something from a list the thing you put inside the box brackets [] should be an integer, eg: [5] . 每当您从列表中访问内容时,放在方括号[]都应为整数,例如: [5] This tells Python that you want the 5th element. 这告诉Python您需要第5个元素。 It cannot ["5"] because 5 in this case would be treated as a string 它不能["5"]因为在这种情况下, 5将被视为字符串

Therefore the line row = str(result[gen_rand_index]) should actually just be row = ... without the call to str . 因此,行row = str(result[gen_rand_index])实际上应该只是row = ...而无需调用str This is why you got the TypeError about list indices 这就是为什么您得到有关列表索引的TypeError的原因

Secondly, as per your description gen_rand_index would return a list of numbers. 其次,根据您的描述gen_rand_index将返回数字列表。

So going by that, why don;t you try this 因此,为什么不尝试呢?

indices_to_pull = gen_rand_index()
file_handle = open("Foodinventory.txt", 'r')
file_contents = file_handle.readlines() # If the file is small and simle this would work fine
answer = []

for index in indices_to_pull:
    answer.append(file_contents[index-1])

Explanation 说明

  1. We get the indices of the file lines from gen_rand_index 我们从gen_rand_index获取文件行的gen_rand_index
  2. we read the entire file into memory using readlines() 我们使用readlines()将整个文件读入内存
  3. Then we get the lines we want, Rememebr to subtract 1 as the list is indexed from 0 然后我们得到想要的行, Rememebr将列表从0索引时减去1

The error you are getting is because you're trying to index a string variable ( line ) with a string index ( row ). 您收到的错误是因为您试图使用字符串索引( row )索引一个字符串变量( line )。 Presumably row will contain something like '[2,3,1]' . 大概row将包含类似'[2,3,1]'

However, even if row was a numerical index, you're not indexing what you think you're indexing. 但是,即使row是数字索引,也不会索引您认为要索引的内容。 The variable line is a string, and it contains (on any given iteration) one line of the file. 变量line是一个字符串,它包含(在任何给定的迭代中)文件的一行。 Indexing this variable will give you a single character. 索引此变量将给您一个字符。 For example, if line contains green $5 , then line[2] will yield 'e' . 例如,如果line包含green $5 ,则line[2]将产生'e'

It looks like your intent is to index into a list of strings, which represent all the lines of the file. 看来您的意图是索引到代表文件所有行的字符串列表。

If your file is not overly large, you can read the entire file into a list of lines, and then just index that array: 如果文件不是太大,则可以将整个文件读入行列表,然后仅索引该数组:

with open('file.txt') as fp:
    lines = fp.readlines()

print(lines[2]).

In this case, lines[2] will yield the string 'blue $6\\n' . 在这种情况下, lines[2]将产生字符串'blue $6\\n'

To discard the trailing newline, use lines[2].strip() instead. 要丢弃尾随的换行符,请改用lines[2].strip()

I'll go line by line and raise some issues. 我将逐行介绍一些问题。

row = str(result[gen_rand_index]) #result[gen_rand_index] gives me the random list of numbers

Are you sure it is gen_rand_index and not gen_rand_index() ? 您确定它是gen_rand_index而不是gen_rand_index()吗? If gen_rand_index is a function, you should call the function. 如果gen_rand_index是一个函数,则应调用该函数。 In the code you have, you are not calling the function, instead you are using the function directly as an index. 在您拥有的代码中,您没有在调用函数,而是直接将函数用作索引。

file = open("Foodinventory.txt", 'r')
for line in file:
    print(line[row])
file.close()

The correct python idiom for opening a file and reading line by line is 用于打开文件并逐行读取的正确python习惯用法是

with open("Foodinventory.txt.", "r") as f:
    for line in f:
        ...

This way you do not have to close the file; 这样,您不必关闭文件。 the with clause does this for you automatically. with子句会自动为您执行此操作。

Now, what you want to do is to print the lines of the file that correspond to the elements in your variable row . 现在,您要做的是打印与变量row的元素相对应的文件row So what you need is an if statement that checks if the line number you just read from the file corresponds to the line number in your array row . 因此,您需要的是一条if语句,该语句检查您刚从文件中读取的行号是否与数组row的行号相对应。

with open("Foodinventory.txt", "r") as f:
    for i, line in enumerate(f):
        if i == row[i]:
            print(line)

But this is wrong: it would work only if your list's elements are ordered. 但这是错误的:仅当列表元素被排序时,它才有效。 That is not the case in your question. 您的问题不是这种情况。 So let's think a little bit. 因此,让我们考虑一下。 You could iterate over your file multiple times, and each time you iterate over it, print out one line. 可以多次遍历文件,每次遍历文件时,请打印出一行。 But this will be inefficient: it will take time O(nm) where n==len(row) and m == number of lines in your file. 但这将是低效的:将花费时间O(nm),其中n == len(row)和m ==文件中的行数。

A better solution is to read all the lines of the file and save them to an array, then print the corresponding indices from this array: 更好的解决方案是读取文件的所有行并将它们保存到数组中,然后从该数组中打印相应的索引:

arr = []
with open("Foodinventory.txt", "r") as f:
    arr = list(f) 
for i in row:
    print(arr[i - 1]) # arrays are zero-indiced

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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