0

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

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

you forgot a separator for links, they will be written as one humongous line with no possibility to separate one from another.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.