要计算csv/.txt文件中的总行数并将其写入Python中的新csv文件,可以按照以下步骤进行操作:
import csv
def count_lines(file_path):
with open(file_path, 'r') as file:
lines = sum(1 for line in file)
return lines
该函数使用了文件对象的迭代器,通过遍历文件的每一行来计算总行数。
input_file = 'input.csv' # 输入文件路径
output_file = 'output.csv' # 输出文件路径
total_lines = count_lines(input_file)
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Total Lines'])
writer.writerow([total_lines])
这里使用了csv库的writer对象来写入csv文件。首先写入表头"Total Lines",然后写入计算得到的总行数。
完整的代码示例:
import csv
def count_lines(file_path):
with open(file_path, 'r') as file:
lines = sum(1 for line in file)
return lines
input_file = 'input.csv' # 输入文件路径
output_file = 'output.csv' # 输出文件路径
total_lines = count_lines(input_file)
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Total Lines'])
writer.writerow([total_lines])
这样,你就可以计算csv/.txt文件中的总行数并将其写入Python中的新csv文件了。
领取专属 10元无门槛券
手把手带您无忧上云