Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print(elem) to .txt files
#1
Hi,

Below is a small script I am working on. It lists all the files in a directory.
I am unsure how to get the print(elem) to save the data to a .txt file.

Any help would be great.
_

import os

'''
    For the given path, get the List of all files in the directory tree
'''
name = input('Please Input The Directory')

def getListOfFiles(dirName):
    # create a list of file and sub directories
    # names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)
    return allFiles


def main():

    dirName = name;

    # Get the list of all files in directory tree at given path
    listOfFiles = getListOfFiles(dirName)

    # Print the files
    #for elem in listOfFiles:
    #    print(elem)

    #print ("****************")

    # Get the list of all files in directory tree at given path
    listOfFiles = list()
    for (dirpath, dirnames, filenames) in os.walk(dirName):
        listOfFiles += [os.path.join(file) for file in filenames]


    # Print the files
    for elem in listOfFiles:
        print(elem)

outF = open("myOutFile.txt", "w")
outF.writelines("main")
outF.close()

#import subprocess
#subprocess.Popen(r'"C:\windows\system32\notepad.exe" "myOutFile.txt"')


if __name__ == '__main__':
    main()
Reply
#2
By default print function writes data to stdout, however, you can redirect it to a file, e.g.

with open("desired_filename.txt", 'w+') as myfile:
    for elem in listOfFiles:
        print(elem, file=myfile)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python print all files which contain specific word in it mg24 5 1,188 Jan-27-2023, 11:20 AM
Last Post: snippsat
  Failing to print sorted files tester_V 4 1,188 Nov-12-2022, 06:49 PM
Last Post: tester_V
  Look for match in two files and print out in the first file Batistuta 0 1,559 Mar-03-2020, 02:27 PM
Last Post: Batistuta

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020