将FOR循环输出追加到列表PYTHON

时间:2020-01-05 09:56:00

标签: python list for-loop

我只是想将for循环的输出写入txt文件

temp = { } # Keys will be the line number, and values will be the lines that contains "IPT" with newline character removed
found_ipt=False
with open("myfile.txt", 'r') as myfile:
    fileNum = 0
    for line in myfile.readlines():
        fileNum +=1
        if line[12:17] == "IPT":
            temp[fileNum] = line.replace('\n', '')
            found_ipt=True
        elif (line[12:15] == "TOP") & found_ipt:
             print(line)
             found_ipt=False

2 个答案:

答案 0 :(得分:1)

您需要在一个单独的循环中而不是嵌套循环中写入文件,或者仅完全删除该嵌套循环。您还应该从close()中删除with open(),它会在完成写入文件后处理关闭操作

with open("ids.txt", "w") as f:
    for filename in glob.glob('/home/*.txt'):
        file_metadata = { 'name': 'files.txt', 'mimeType': '*/*' }
        media = MediaFileUpload(filename, mimetype='*/*', resumable=True)
        file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
        f.write(f'{file.get("id")}\n')
        # or if your Python version is older than 3.6
        f.write(str(file.get("id")) + '\n')

答案 1 :(得分:0)

您不应将相同的变量file用于两个不同的目的。而且您不应该close()with open() as ..打开的任何内容:

links = []
for filename in glob.glob('/home/*.txt'):
    file_metadata = { 'name': 'files.txt', 'mimeType': '*/*' }
    media = MediaFileUpload(filename, mimetype='*/*', resumable=True)
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    links.append(file.get('id'))

with open("ids.txt", "w") as fout:
    fout.write('\n'.join(links))