计算文件中的行数,并计算每行中的数字。然后将其写到输出文件中
代码:
num_lines = 0
with open("Version2_file.txt", 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:")
print(num_lines)
来自文本文件:
1.0,1.123,1.123
1.0,1.123,1.123
1
因此,文本文件中有3行,第1行有3个数字,第2行有3个数字,第3行有1个。
预期:
Number of Lines: 3
Numbers in Line 1: 3
Numbers in Line 2: 3
Numbers in Line 3: 1
实际:
Number of lines: 3
答案 0 :(得分:0)
如何使用line.split(',')
查找每一行中的数字(假设它们总是用逗号分隔)。
i = 0
with open("Version2_file.txt", 'r') as f:
for line in f:
i += 1
j = len(line.split(','))
print('line', i, 'contains', j, 'numbers')
答案 1 :(得分:0)
尝试一下:
with open('Version2_file.txt', 'r') as f:
content = f.readlines()
print('Number of Lines: {}'.format(len(content)))
for i in range(len(content)):
print('Numbers in Line {}: {}'.format(i, len(content[i].split(','))))
输出:
Number of Lines: 3
Numbers in Line 0: 3
Numbers in Line 1: 3
Numbers in Line 2: 1