简体   繁体   English

将嵌套列表中的整数输出到文本文件中的字符串

[英]Outputting integers in a nested list to string in a text file

So I currently have this code at the end of my program that allows the user to save the text file.所以我目前在我的程序末尾有这个代码,允许用户保存文本文件。 I have no idea how to convert the data to string and that is what is giving me the error if i try to use this code.我不知道如何将数据转换为字符串,如果我尝试使用此代码,这就是给我错误的原因。

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.")

However, my original_graph is a nested list with only integer values, ex: [0,1,1,0],[0,0,0,1],[0,0,1,0]但是,我的original_graph是一个只有整数值的嵌套列表,例如: [0,1,1,0],[0,0,0,1],[0,0,1,0]

How would I make it so that the text file is looks something like我如何才能使文本文件看起来像

0110 0001 0010

in the text file after I save it?保存后在文本文件中? Also, is there a way to prompt the user if they were overwrite an existing file?另外,有没有办法提示用户是否覆盖了现有文件?

Thank you for your time.感谢您的时间。

A compact way to write this is using list comprehensions.编写此内容的一种紧凑方法是使用列表推导式。 For convenience, I'll use stdout as the output file.为方便起见,我将使用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')

output输出

0110
0001
0010

To save the data to a file whose name is a string stored in destination , just do:要将数据保存到名称为存储在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')

To check if a file already exists, use the os.path.exists function.要检查文件是否已经存在,请使用os.path.exists函数。 If you need further help on this aspect please ask a new question.如果您需要这方面的进一步帮助,请提出一个新问题。 Stack Overflow questions should contain a single question in order to maximize their usefulness for future readers. Stack Overflow 问题应该包含一个问题,以便最大限度地为未来的读者提供有用的信息。

Please check this works请检查这个作品

original_graph=[[0,1,1,0],[0,0,0,1],[0,0,1,0]]
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(str(i) for i in original_graph))
else:
    print("End of program.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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