【问题标题】:is it possible to import a function to python, then take the outputs from that function and print them to a .txt file?是否可以将函数导入 python,然后从该函数获取输出并将它们打印到 .txt 文件?
【发布时间】:2022-10-31 00:24:01
【问题描述】:

是否可以将函数导入 python,然后从该函数获取输出并将它们打印到 .txt 文件?没有输入的代码可以正常工作,但是当导入函数时,它首先运行,然后是后续代码。不打印到txt。文件

## code with import                                                                             
import use_test 
animals = []
with open('readme.txt', 'w') as f:
for line in animals:
    f.write(line)
    f.write('\n')
print(animals)

print("fin")
## code without import 
animals1 = input("test")
with open('readme.txt', 'w') as f:
for line in animals1:
    f.write(line)
    f.write('\n')
print(animals1)

print("fin")

【问题讨论】:

  • 在第一个代码示例中,animals 是一个空列表,因此 for 循环 for line in animals 不会执行。

标签: python


【解决方案1】:

没有任何内容写入文件,因为您正在遍历一个空列表 (animals)。

## code with import                                                                             
import use_test 
animals = []  # <--- EMPTY
with open('readme.txt', 'w') as f:
for line in animals:
    f.write(line)
    f.write('
')
print(animals)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多