Python 提取文件内容并转换为字符串列表
您可以使用 Python 的文件操作和字符串处理来实现该功能。下面是一个示例代码:
def read_file(file_name):
with open(file_name, 'r') as file:
lines = file.readlines()
return [line.strip() for line in lines]
file_name = '1.txt'
strings = read_file(file_name)
output = '{' + ','.join([''{}''.format(s) for s in strings]) + '}'
print(output)
运行上述代码,将会输出{'aa','ab','ac'}。该代码首先定义了一个read_file函数,用于读取文件并返回每一行的字符串列表。然后,通过调用该函数读取文件1.txt的内容,并使用列表推导式将每个字符串添加到一个新的列表中。最后,使用字符串的join方法将字符串列表连接起来,并使用格式化字符串来添加单引号,形成最终的输出字符串。
原文地址: https://www.cveoy.top/t/topic/qr2R 著作权归作者所有。请勿转载和采集!