Python Forum
print console output to a csv - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: print console output to a csv (/thread-15999.html)



print console output to a csv - deep_logic - Feb-10-2019

Hi all,
I have googled ad nauseaum, but I can't seem to find a solution for printing contents of a folder to a .csv
###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))])
    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")
I get an error, "Traceback (most recent call last):
File "C:\Users\Randy\Documents\5CRIPT5\ListFiles.py", line 26, in <module>
with Path(csvfilename).open(mode="w+") as p:
NameError: name 'Path' is not defined

Kinda stuck here. It looks as though path should be a variable?
I'm using IDLE 3.7 and on WINDOWS 10, Lenovo Inspiron

Thanks,


RE: print console output to a csv - scidam - Feb-10-2019

(Feb-10-2019, 04:31 AM)deep_logic Wrote: NameError: name 'Path' is not defined

You didn't import Path:

from pathlib import Path



RE: print console output to a csv - deep_logic - Feb-10-2019

(Feb-10-2019, 04:38 AM)scidam Wrote:
(Feb-10-2019, 04:31 AM)deep_logic Wrote: NameError: name 'Path' is not defined

You didn't import Path:

from pathlib import Path

That did work, however, It's not creating the .csv file.

Still grindin'...


RE: print console output to a csv - deep_logic - Feb-21-2019

Just a follow up. It seems that the network at my work has been locked down. So, I'm not able to script codes in python and create files and such. I can do SOME things, but I'm the little fish in the proverbial big pond.

FWIW, I did use this code to create a .txt list and just use that to populate my excel file.

Many thanks for the help and I'm grateful for the pythonista community.