如何在python中循环处理文本文件

2024-06-17 16:16:24 发布

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

我需要一个循环文件的帮助:

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[]等等。你知道吗


Tags: 文件intxtforlineopenappendlst
2条回答
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

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

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.

相关问题 更多 >