Click here to Skip to main content
14,735,180 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
There is a working directory where I downloaded 7 PDF files. The files are sorted by modification time so the order is: (file1.pdf, file2.pdf .. file7.pdf).

There is a text file (description.txt) that contains 7 lines.

Like this:

description1
description2
.
.
description7


I have a text file (helloworld.txt) what I want to append every line with {filename} {filesize} {description} like this:

{file1.pdf} {filesize of file1.pdf} {description1}
{file2.pdf} {filesize of file2.pdf} {description2}
.
.
{file7.pdf} {filesize of file7.pdf} {description7}

What I have tried:

I have written a script in Python:

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


I have run the code but the helloworld.txt not correct. The result is the following:

file1.pdf 0.08 description1

file6.pdf 0.21 description2

file3.pdf 0.14 description3

file2.pdf 0.02 description4

file5.pdf 0.14 description5

file7.pdf 0.15 description6

file4.pdf 0.2 description7


The filename order is not correct (conjugated with file size). The order is not the same as in the folder order (download order). (I did not change it. It sort by modification time.)
My OS is: Linux Lubuntu 20.04LTS

Can somebody solve this problem?
Posted
Updated 3-Jun-20 2:56am
v2
Comments
Richard MacCutchan 3-Jun-20 8:27am
   
It will only work if both lists are in the same order. A better idea is to read the descriptions first so you can match the file names as you get them from the system call.

Looking at the documentation, glob calls os.listdir[^], and listdir doesn't return the files in any specific order:
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order.
You will need to sort the returned list yourself.
   
Why not try the os.walk() function? It's another way of walking through directories and returning the file path and file name. There's no guarantee it'll work the way you want, but it's worth a shot.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900