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

其他-在写入文本文件时如何在python中应用For Loop

(其他 - How to apply a For Loop in python while writing in a text file)

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

我是python的新手,在使用For Loop时遇到麻烦。我正在尝试获取一些pdf文件的文档信息,并将该信息记录在一个文本文件中。在执行期间,它在输出窗口中显示所有文件名,但是如果我想将其写入文本文件,则仅写入单个文件数据。

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

使用清单。

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