你如何在python中循环文本文件

时间:2018-08-26 11:48:21

标签: python loops

我需要循环文件的帮助:

inputa = int(input('How many days of data do you have? '))
print('Average Temperatures:')

if inputa == 1:
  lst1 = []  
  lst = []  

  for line in open('temps1.txt'):
    lst1.append(line.rstrip())
  lst = lst1      

elif inputa == 2:
  lst1 = []
  lst2 = []
  lst = []

  for line in open('temps1.txt'):
    lst1.append(line.rstrip())

  for line in open('temps2.txt'):
    lst2.append(line.rstrip())

  lst = lst1+lst2

elif inputa == 3:
  lst1 = []
  lst2 = []
  lst3 = []
  lst = []

  for line in open('temps1.txt'):
    lst1.append(line.rstrip())

  for line in open('temps2.txt'):
    lst2.append(line.rstrip())

  for line in open('temps3.txt'):
    lst3.append(line.rstrip())

lst = lst1 + lst2 + lst3

有没有一种方法可以遍历文件。例如,根据用户的输入,我希望它们为temps1.txttemps2.txttemps3.txt,依此类推。我也想拥有lst1[]lst2[]lst3[]等。

2 个答案:

答案 0 :(得分:0)

import glob
g=glob.glob("*") #This selects every file in directory, if you want the only the ones starting with "temps", then write "temps*"
for index, line in enumerate(g):
    print(g)
    #do stuff with files here

g是您的文件列表。最后一个for循环只是对它们的循环。这有帮助吗?

评论后的修改

这对我有用:

import glob
g=[]
for x in range(inputdata):
    select = "*"+str(x)
    exp_g=glob.glob(select)
    g.extend(exp_g)
g

答案 1 :(得分:0)

创建列表列表,而不是单独的列表。这有助于更好地管理事物。然后循环遍历文件,并将内容放入先前创建的列表列表的每个子列表中。

inputa = int(input('How many days of data do you have? '))
print('Average Temperatures:')

lst = [[] for _ in range(inputa)]

for i in range(inputa):
    for line in open(f'temps{i+1}.txt'):
        lst[i].append(line.rstrip())

print(lst)  # List of lists.
print([item for sublist in lst for item in sublist])  # Flattened list.