Warm tip: This article is reproduced from serverfault.com, please click

How to apply a For Loop in python while writing in a text file

发布于 2020-11-28 05:33:17

I am a new learner in python and got stuck while working with For Loop. I am trying to get the Document information of some pdf files and write down the Information in a text file. During Execution it shows all the file names in the output window, but writes only single file data if I want to write it in a text file.

import PyPDF2
import os

d = "C:\\New folder"
for filename in os.listdir(d):
        a = PyPDF2.PdfFileReader(d + "\\" + filename, strict= False)
        c = a.getDocumentInfo()
        g = filename + " : " + str(c)
        print(g)
        with open("check.txt", "w") as f:
                f.writelines(g + "\n")
Questioner
Vishal Mishr
Viewed
0
Abhishek Rai 2020-11-28 15:20:21

Use a list.

import PyPDF2
import os

d = "C:/Users/Abhi/Downloads/pdf"
g_list = []
for filename in os.listdir(d):
        a = PyPDF2.PdfFileReader(d + "\\" + filename, strict= False)
        c = a.getDocumentInfo()
        g = filename + " : " + str(c)
        g_list.append(g)

with open("check.txt", "w") as file:
        file.write("\n".join(item for item in g_list))

Output:-

[Richard_J._Evans]_Lying_About_Hitler_History,_Ho(BookFi).pdf : {'/CreationDate': "D:20090120170100+02'00'", '/Creator': 'Acrobat Capture 3.0', '/Producer': 'Adobe PDF Library 4.0', '/ModDate': "D:20090120170100+02'00'"}
[Richard_Sakwa]_The_Quality_of_Freedom_Khodorkovs(b-ok.cc).pdf : {'/CreationDate': 'D:20090927052507', '/Creator': 'Advanced PDF Repair at http://www.datanumen.com/apdfr/', '/ModDate': 'D:20090927052507', '/Producer': 'Advanced PDF Repair at http://www.datanumen.com/apdfr/'}
[Robert_Sewell]_A_Forgotten_Empire_-_Vijayanagar_-(BookFi).pdf : {'/Producer': 'htmldoc 1.8.11 Copyright 1997-2001 Easy Software Products, All Rights Reserved.', '/CreationDate': 'D:20010327220822Z', '/Title': ' A Forgotten Empire: Vijayanagar; A Contribution to the History of India', '/Author': 'Robert Sewell'}
[Ronald_M._Davidson]_Indian_Esoteric_Buddhism_A_S(BookFi).pdf : {'/Title': 'Indian Esoteric Buddhism. A Social History of th