如何在写入文本文件时在 python 中应用 For 循环

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

我是 python 的新手,在使用 For 循环时卡住了。 我正在尝试获取一些 pdf 文件的文档信息并在文本文件中记下这些信息。 在执行期间,它在输出中显示所有文件名 window,但如果我想将其写入文本文件,则只写入单个文件数据。

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")

使用列表。

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))

输出:-

[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