【问题标题】: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?检索两个单独文件夹(目录)中的文件列表。如何将终端中的打印内容打印到新的文本文档中?
【发布时间】:2019-12-17 23:05:59
【问题描述】:

我有一个函数可以从用户在我的 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.

【问题讨论】:

  • 您问的是如何将数据写入文件的基本问题吗?数据的来源无关紧要。许多 python 教程都介绍了写入文件。
  • 这能回答你的问题吗? Writing a list to a file with Python
  • 正确。我想将数据写入文件。

标签: python python-3.x user-interface tkinter


【解决方案1】:

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

Python 3 print() 声明

官方文档: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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2021-08-02
    • 2017-04-05
    相关资源
    最近更新 更多