读取文件的每一行并为每一行指定一个ID-Python

读取文件的每一行并为每一行指定一个ID-Python,python,Python,我需要读取输入文件的每一行,并为每一行分配自己的ID,以便以后可以识别它 如果我知道文件将有多少行,或者如果它很短,但我需要使它能够获取任何行数的文件,那么这将很简单 例如,我正在使用的试用文件包含以下内容: somewhere over rainbow bluebirds fly birds fly over rainbow why why double time population long takes population double size whoa full rainbow wa

我需要读取输入文件的每一行,并为每一行分配自己的ID,以便以后可以识别它

如果我知道文件将有多少行,或者如果它很短,但我需要使它能够获取任何行数的文件,那么这将很简单

例如,我正在使用的试用文件包含以下内容:

somewhere over rainbow bluebirds fly birds fly over rainbow why why
double time population long takes population double size
whoa full rainbow way double rainbow double rainbow way
我需要单独阅读每一行,并给它分配一个ID,以便
在彩虹上方的某个地方蓝鸟飞鸟飞过彩虹为什么
被分配ID 1等等

我似乎找不到一种动态创建变量/变量名的方法,我也不知道有任何其他自动分配ID的方法

任何帮助都将不胜感激

for line_no,line in enumerate(file,1):
    ...
line\u no
将是您的
id
。。。我想


line\u no
将是您的
id
。。。我想

您可以将这些行存储在字典中,以键作为ID:

with open(myfile, 'r') as f:
    lines = {i: line for i, line in emumerate(f, 1)}
这将生成一个以1中的数字作为键的字典:

{
    1: "somewhere over rainbow bluebirds fly birds fly over rainbow why why",
    2: "double time population long takes population double size",
    3: "whoa full rainbow way double rainbow double rainbow way"
}

的第二个参数设置枚举的起始编号,因此在本例中,我们从一开始索引;如果未提供起始编号,则默认为零。

您可以将行存储在字典中,键作为ID:

with open(myfile, 'r') as f:
    lines = {i: line for i, line in emumerate(f, 1)}
这将生成一个以1中的数字作为键的字典:

{
    1: "somewhere over rainbow bluebirds fly birds fly over rainbow why why",
    2: "double time population long takes population double size",
    3: "whoa full rainbow way double rainbow double rainbow way"
}

的第二个参数设置枚举的起始编号,因此在本例中,我们从一开始索引;如果没有提供起始编号,则默认为零。

您可以使用dict存储带有id的行

这里有一个例子

rows = {}
n = 1
with open(filename) as f:
    for line in f:
        rows[n] = line
        n += 1

您可以使用dict存储带有id的行

这里有一个例子

rows = {}
n = 1
with open(filename) as f:
    for line in f:
        rows[n] = line
        n += 1

我可能只会使用一个列表,位置作为ID:

ls = []
with open(file, 'r') as f:
    for line in f:
        ls.append(line.rstrip()) 

我可能只会使用一个列表,位置作为ID:

ls = []
with open(file, 'r') as f:
    for line in f:
        ls.append(line.rstrip()) 

字典似乎是解决这个问题的好办法。我还将使用enumerate自动获取行号

file_name = 'text.txt'
with open(file_name, 'r') as f:
    indexes = {index:value for index, value in enumerate(f)}
>>>indexes[0]
'somewhere over rainbow bluebirds fly birds fly over rainbow why why\n'

字典似乎是解决这个问题的好办法。我还将使用enumerate自动获取行号

file_name = 'text.txt'
with open(file_name, 'r') as f:
    indexes = {index:value for index, value in enumerate(f)}
>>>indexes[0]
'somewhere over rainbow bluebirds fly birds fly over rainbow why why\n'

你要找的是一本字典或一份清单。这是家庭作业吗?闻起来很像家庭作业。我重新打开了这个问题,因为重复的目标已被删除。你要找的是字典或列表。这是家庭作业吗?闻起来很像家庭作业。我重新打开了这个问题,因为重复的目标已被删除。