git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

print console out to a txt or csv file


Hi all,
I have been working on some code to list the files of a folder that has .pdf extension. I have the basic code to create a list, but it prints that list to the console. I'd like my code to write a txt file that contains that list (to later import into excel).

###A script to list pdf files in a folder
###gisdude 02/09/19
###
import os, sys, glob, csv, pathlib

###First, let's change the dir with os

os.chdir("C:\\Users\\Randy\\Documents\\BOOKS")

###Second, let's now get the list of files in this directory

files = glob.glob('*.pdf')
for file in glob.glob("*.pdf"):
    print (file)

###This prints to the IDLE console
###But, I want to print to a csv file

####for filename in glob.iglob ('*.pdf'):
                            ###with open('Listofpdf', 'filename') as csvfile:
                            ###writer = csv.writer(csvfile, delimter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
                            ###writer.writerrow([('{}\t.format(elem))])
    from pathlib import Path
    searchdir = "C:\\Users\\Randy\\Documents\\BOOKS"
    csvfilename = "listofpdf.txt"

    with Path(csvfilename).open(mode="w+") as p:
        files = Path(searchdir).glob('*.py')
        p.write(f"{' '.join(str(file) for file in files)}\n")

At this point, the pathlib mod seems like it should create the file?

I'm on WINDOWS 10 and IDLE 3.7.

Thanks for any help,
R`