Writing filesize and filepath of a folder to a text file with Python 3.7

I am using Python 3.7. I want to check the file sizes of a directory with the file path to a text file.

This is my code:

import os
import glob


# folder path
folderpath = 'C:/Test'

# Get a list of files in my folder
list_of_files = filter( os.path.isfile,
                        glob.glob(folderpath + '*') )

# get list of files with the size in my folder
files_with_size = [ (file_path, os.stat(file_path).st_size)
                    for file_path in list_of_files ]

# Iterate over the files and write them to a file
for file_path, file_size in files_with_size:
    with open('c:/Test/filesize.txt', 'w') as f:
        print(file_size, ' -->', file_path)

I can print the result in the Python console, but I cannot manage to write my result to a text file. Can anybody help me?

Regards, Jan

1 answer

  • answered 2022-05-04 09:40 Daweo

    I would ameloriate your code following way

    for file_path, file_size in files_with_size:
        with open('c:/Test/filesize.txt', 'a') as f:
            print(file_size, ' -->', file_path, file=f)
    

    changes: use a (append) mode and use f as value for named argument file of print function.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum