逐行读入文件并将每一行的内容存储在一个列表中以供进一步处理

2024-04-25 20:02:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表生成file1和file2(其中所有字母都是随机值)。 每个文件中的行是同一对象的值。

例如,对象1具有以下值,所有2个文件的值都来自第1行

  object1:  
    a, b, c, d, e, f
    g, h, i, j, k, l

$ cat file1
a, b, c, d, e, f  # line1 - object1
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f

$ cat file2
g, h, i, j, k, l # line1 - object1
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l
g, h, i, j, k, l

现在我有一个脚本,它有一些列表,需要在循环中包含来自这两个文件的值

daytime = now.strftime("%A")
varlist1 = [a, b, c, d, e, f]
varlist2 = [g, h, i, j, k, l]
static1 = [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

for li1,li2,st1 in zip(varlist1, varlist2, static1)
    if (li1 != 0 and li2 == 0 and daytime == st1):
        print "Go"
    else:
        print "NoGo"

我需要逐行读取文件并从列表varlist1、varlist2中的文件传递变量,然后处理循环中的每一行文件

实现这一目标的最佳方法是什么。我没能找到一个快速的方法来实现这一点?你知道吗

非常感谢


Tags: 文件对象列表file1catfile2line1object1
1条回答
网友
1楼 · 发布于 2024-04-25 20:02:14

I need to read the file line by line and pass the variable from the file in the list varlist1,varlist2, then process each line of the files in the loop

我不完全确定你想在这里完成什么,但我可以给你一个演示,应该很容易调整,以满足您的需要。我还假设ab。。。在这个演示中应该是整数。您可以这样逐行处理文件:

f1 = open('file1', 'r')
f2 = open('file2', 'r')

for i in range(3): # your actual conditions go here
    # read in next line from each of the files and store them in a list of ints
    varlist1 = f1.readline().strip().split(', ')
    varlist1 = [int(x) for x in varlist1] # use float(x) here if a,b,... are floats
    varlist2 = f2.readline().strip().split(', ')
    varlist2 = [int(x) for x in varlist2] # use float(x) here if g,h,... are floats
    # do something more interesting with varlist1, varlist2 here
    # than just printing them
    print(varlist1)
    print(varlist2)

f1.close()
f2.close()

但是我不逐行处理文件,而是准备如下所有变量列表:

with open('file1', 'r') as f1:
    data1 = f1.read().splitlines()
with open('file2', 'r') as f2:
    data2 = f2.read().splitlines()

varlists1 = [[int(x) for x in y.split(', ')] for y in data1] # or float(x) ...
varlists2 = [[int(x) for x in y.split(', ')] for y in data2]

现在,您可以执行以下操作:

for varlist1, varlist2 in zip(varlists1, varlists2):
    for li1,li2,st1 in zip(varlist1, varlist2, static1):
        # your code here

相关问题 更多 >

    热门问题