Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This code shows a directory's files' sizes and names. I want to add {description} from a text file (descriptiontext).




The original code is the following:



Python
import os
import glob

textfilename = 'textfilename'

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
        textfile.write(f'File {filename} has size {filesize} bytes\n')  # \n means newline


The task is the following:

Append the last line with {description} what is derived from another text file named descriptiontext.
So every line of the descriptiontext has taken place in the last line at the {description} place with for loop.

I do not know how to conjugate two for loops.

What I have tried:

I have tried to nest a second for loop inside the first but it only adds the last element of the descriptiontext, the last line.

The nested loop was:

Python
with open(descriptiontext, 'r') as textfile2:
            for line in textfile2:
                description = line
Posted
Updated 21-May-20 6:03am

1 solution

You can use the readline method to read a file one line at a time: see 7. Input and Output — Python 3.7.7 documentation[^]. So your code should be something like:
Python
descriptiontext = open("descriptiontext", '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
        description = descriptiontext.readline()
        textfile.write(f'File {filename} has size {filesize} bytes : {description}\n')  # \n means newline
 
Share this answer
 
v2
Comments
folza 21-May-20 13:45pm    
The solution is almost complete good, only the "as textfile" section does not need it at the first line.
Thanks!
Richard MacCutchan 22-May-20 3:42am    
Corrected.

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