首页 > 解决方案 > 检索两个单独文件夹(目录)中的文件列表。如何将终端中的打印内容打印到新的文本文档中?

问题描述

我有一个函数可以从用户在我的 Tkinter GUI 窗口中选择的两个单独的目录(文件夹)中检索文件列表。两个目录中所有文件的列表都可以在 Visual Studio 代码终端中打印,但是如何从这两个目录中获取文件列表以打印到新的文本文件?

    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.

标签: pythonpython-3.xuser-interfacetkinter

解决方案


有两种简单的方法可以做到这一点,都使用open()函数。官方文档在这里:https ://docs.python.org/3/library/functions.html 。

Python 3print()语句

官方文档:https ://docs.python.org/3/library/functions.html

在 python 3 中,print 语句是一个带有附加参数的函数。这些参数之一在这里很有帮助:file参数。

要打印到文件:

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

传统.write()功能

官方文档:https ://docs.python.org/3/tutorial/inputoutput.html

write 函数有一个参数:一个字符串。要写入文件,首先open()是它。

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

推荐阅读