简体   繁体   中英

List of files in two separate file folders (directories) is retrieved. How do I get what prints in the terminal to print into a new text document?

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM