I have a folder with pdf files and I have a text file: helloworld.txt and another txt file description.txt
The helloworld.txt is empty by default. The description.txt contains the files' description. Every line one description.
I want that in every line in helloworld.txt contain the pdf files' names, files' sizes, and descriptions of the files.
So every helloworld.txt line looks like this: {filename} {filesize} {description}
So many lines like pdf elements in the folder.
I have got the following code snippet:
import os
import glob
textfilename = 'helloworld.txt'
descriptiontext = open("description.txt", 'r')
with open(textfilename, 'a') as textfile: # Open the text file for appending
for filename in glob.iglob('*.pdf'): # For every file in the current directory matching '*.pdf'
stat = os.stat(filename) # os.stat gets various file statistics
filesize = stat.st_size/1024/1024
filesize = round(filesize,2)
description = descriptiontext.readline()
textfile.write(f'{filename} {filesize} {description} \n') # \n means newline
The script is working almost perfectly. The {filename}{filesize}{description} at the good place.
The problem: the pdf folder set to sort by modification time (how I downloaded from a site) and it looks like in the folder (Lubuntu 20.04 LTS) but after I run the script the {filename} sequence is not the same as the folder's sequence in the helloworld.txt file.
How to modify the code to write the {filename} at the same sequence in the helloworld.txt like in the folder sequence sort by modification time?