因此,我目前在程序的末尾有此代码,该代码允许用户保存文本文件。我不知道如何将数据转换为字符串,如果我尝试使用此代码,这就是给我的错误。
save = input("Would you like to save the latest generation? ('y' to save):")
if save == 'y':
destination = input("enter destination file name:")
with open(destination, 'w') as file:
file.writelines('\t'.join(i) + '\n' for i in original_graph)
else:
print("End of program.")
但是,myoriginal_graph
是一个只有整数值的嵌套列表,例如:[0,1,1,0],[0,0,0,1],[0,0,1,0]
我将如何使文本文件看起来像
0110 0001 0010
保存后在文本文件中保存?另外,是否有一种方法可以提示用户是否覆盖了现有文件?
感谢您的时间。
一种简单的写方法是使用列表推导。为了方便起见,我将其stdout
用作输出文件。
import sys
original_graph = [
[0, 1, 1, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
]
f = sys.stdout
rows = [''.join([str(u) for u in row]) for row in original_graph]
f.write('\n'.join(rows) + '\n')
输出
0110
0001
0010
要将数据保存到名称是存储在中的字符串的文件中destination
,请执行以下操作:
rows = [''.join([str(u) for u in row]) for row in original_graph]
with open(destination, 'w') as f:
f.write('\n'.join(rows) + '\n')
要检查文件是否已经存在,请使用该os.path.exists
功能。如果您在这方面需要进一步的帮助,请提出一个新问题。堆栈溢出问题应包含一个问题,以最大程度地提高其对未来读者的实用性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句