简体   繁体   中英

Append FOR Loop output to List PYTHON

i'm just trying to write output of for loop to txt file

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 = []
    links.append(file.get('id'))
    with open("ids.txt", "w") as file:
        for e in links:
            file.write(str(e))
            file.close()

You need to write to the file in a separate loop, not nested loop, or just remove the nested loop entirely. You should also remove close() from with open() , it handles the closing after the writing to the file is done

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')

You should not use the same variable file for two different purposes. And you should not close() anything you open with 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM