简体   繁体   English

Python:枚举txt文件中的行,后跟逗号

[英]Python: Enumerate lines in txt file followed by comma

I have a text file that contains comma delimited coordinates as floats in the following format.我有一个文本文件,其中包含逗号分隔的坐标作为浮点数,格式如下。

0.5,0.8,1.0
0.6,0.9,1.2

I need to enumerate each line within the text file for which I have read the file and prepended a count to each line using the following.我需要枚举我已读取文件的文本文件中的每一行,并使用以下内容为每一行添加一个计数。

infile = open('coordinates.txt', 'r')
line = infile.readlines()
infile.close()
count = ['%d %s' % (i, line) for i, line in enumerate(lines, 1)]
numbered_coordinates = open('coordinates.txt', 'w')
numbered_coordinates.writelines(str("".join(count)))
numbered_coordinates.close()

Which outputs the following.输出以下内容。

1 0.5,0.8,1.0
2 0.6,0.9,1.2

However, I require a comma after each number in the count, I have tried inserting a comma to the count parenthesis and by adding it as a string when writing the file.但是,我在计数中的每个数字后都需要一个逗号,我尝试在计数括号中插入一个逗号,并在写入文件时将其作为字符串添加。

numbered_coordinates.writelines(str(",".join(count)))
count = ['%d %s' % (i, line) + ', for i, line in enumerate(lines, 1)]

Which gives.这使。

,1  0.5,0.8,1.0
,2 0.6,0.9,1.2

Seems simple enough but has cost me consdiderable time!!看起来很简单,但花了我很多时间!!

I dont really understand what output you are trying to get but if u desire this output:我真的不明白你想得到什么 output 但如果你想要这个 output:

1,0.5,0.8,1.0
2,0.6,0.9,1.2

than simply change而不是简单地改变

count = ['%d %s' % (i, line) for i, line in enumerate(lines, 1)]

to

count = ['%d,%s' % (i, line) for i, line in enumerate(lines, 1)]

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

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