-2

I have a function that retrieves a list of files from two separate directories (file folders) that the user chooses in my Tkinter GUI window. The list of all the files in both of the directories prints in the visual studio code terminal just fine, but how do I get the list of files from these two directories to print to a new text file?

    Input_1 = entry_field1.get() #Retrieving what the user inputed into entry field 1.
    Input_2 = entry_field2.get() #Retrieving what the user inputed into entry field 2.
    file_list_1=os.listdir(Input_1) #Listing the files from directory 1.
    file_list_2=os.listdir(Input_2) #Listing the files from directory 2.
    print (file_list_1) #Printing the files in the terminal window.
    print (file_list_2) #Printing the files in the terminal window.
khelwood
  • 55,782
  • 14
  • 81
  • 108
markm0311
  • 15
  • 5
  • Are you asking the basic question of how to write data to a file? The source of the data is irrelevant. Writing to files is covered in many python tutorials. – Bryan Oakley Dec 17 '19 at 23:19
  • Does this answer your question? [Writing a list to a file with Python](https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python) – blueteeth Dec 17 '19 at 23:28
  • correct. I want to write data to a file. – markm0311 Dec 18 '19 at 00:24

1 Answers1

0

There are two simple ways to do this, both using the open() function. The official documentation is here: https://docs.python.org/3/library/functions.html.

Python 3 print() Statement

Official docs: https://docs.python.org/3/library/functions.html

In python 3, the print statement is a function with additional parameters. One of these parameters is helpful here: the file parameter.

To print to file:

>>> print('hello', file = open('hello.txt','w'))

Traditional .write() function

Official docs: https://docs.python.org/3/tutorial/inputoutput.html

The write function takes one argument: a string. To write to a file, first open() it.

>>> my_File = open('hello.txt', 'w') # the 'w' means that we're in write mode
>>> my_File.write('This is text')    # Now we need to close the file
>>> my_File.close()