如何打开三个内部具有相同数据序列的文件,所有这些文件数据都应在循环内运行。该循环将捕获文件中的值。先读取第一个文件数据然后读取第二个文件,然后读取如何在我现有的代码中使这个工作...
def memberStatus():
inputFile = open('Members.txt', 'r')
inputFile = open('Members1.txt', 'r')
inputFile = open('Members2.txt', 'r')
with inputFile as myFile:
for number, line in enumerate(myFile):
line=(line.rstrip()).split()
rawList=[]
rawList.append(line)
print("raw list : ", rawList)
intLine1 = [str(elem) for elem in rawList]
intLine1 = ''.join(intLine1)
AgeItem = intLine1[2:4]
winLoosItem = intLine1[8:9]
logInItem = intLine1[13:16]
GenderItem = intLine1[20:26]
incomeItem = intLine1[30:33]
这三个文件应该在“with inputFile as myFile:”loop
中运行答案 0 :(得分:2)
这样做:
inputFile = open('Members.txt', 'r')
inputFile = open('Members1.txt', 'r')
inputFile = open('Members2.txt', 'r')
您每次只需将inputFile
名称重新分配给其他文件。
许多可能的方法之一是例如将文件名放入列表然后遍历列表。
inputFiles = ['Members.txt', 'Members1.txt', 'Members2.txt']
for membersFile in inputFiles:
myFile = open(membersFile, 'r')
# And rest of code goes in here.
myFile.close()
编辑:
@SergeBallesta是正确的,你通常宁愿使用with
语句对文件进行操作,因为它非常方便和易于使用,在这个例子中它会这样:
inputFiles = ['Members.txt', 'Members1.txt', 'Members2.txt']
for membersFile in inputFiles:
with open(membersFile, 'r') as myFile:
# And rest of code goes in here.
一个人应该自己决定对他和他/她来说更方便的事情。
答案 1 :(得分:2)
def memberStatus():
for name in ['Members.txt', 'Members1.txt', 'Members2.txt']:
with open(name, 'r') as myFile:
# do stuff