如何从文件中获得输出,使元素之间有逗号

  • 本文关键字:元素 之间 输出 文件 python
  • 更新时间 :
  • 英文 :


我想在文件中的元素之间添加逗号。现在它的输出都挤在一起了。这是一个更大计划的一部分。有人能帮忙吗?

代码:

def export_emp():
f = open('output.txt','a+')
for i in range (len(employee_List)):
f.write(str(employee_List[i][0]))
f.write(str(employee_List[i][1]))
f.write(str(employee_List[i][2]))
f.write(str(employee_List[i][3]))
f.write(str(employee_List[i][4]))
f.close()
def add_empFile():
output=open('output.txt','r')
file=output.read()
output.close()
print(file)

您可以定义一个函数来在文件中添加逗号:

def write_to_file(file,text):
if text is not None:
file.write(text+",")

write()内容的末尾添加逗号,如下所示:

f.write(str(employee_List[i][0]) + ",")

如果要在所有employee_List之间添加逗号,您只需迭代employee_List中的所有元素,然后使用join方法添加逗号,连接它们时不需要指定所有索引。

def export_emp():
with open('output.txt','a+') as f:
string = ','.join([str(x) for x in employee_List])
f.write(string)

您可以使用逗号连接并在末尾写入文件:

with open('output.txt','a+') as f:
for x in employee_List:
to_save = ', '.join([str(x[i]) for i in range(5)])
f.write(to_save)

另外,使用with open(...)打开文件,所以您不需要担心关闭文件。

最新更新