【发布时间】:2022-01-14 09:11:16
【问题描述】:
我是 python 新手,我想编写一个脚本来操作从 Tera Term 获得的 csv 文件。该文件有 3 列,我想在每 160 行拆分第 3 列并将它们水平堆叠。数据太长,无法手动完成,我相信 python 将是解决这个问题的最佳方法。 下表是 input.csv 文件的样子
下面是我的python脚本,
#!/usr/bin/python
""" Parses USS Template project UART data (src.csv) and store result in out.csv"""
import re
import struct
import sys
def decode_file(file_in_name, file_out_name):
# Open File Input and Output Files
input_file = open(file_in_name, "r")
target_file = open(file_out_name, "w")
# Iterate through the data
count=0
for line in input_file:
# Remove New Line
line = line.rstrip("/n")
# Remove Spaces in front
line = line.lstrip(" ")
# Remove White space and tabs
pattern = re.compile(r"\s+")
clean_line = re.sub(pattern, " ", line)
# Split the line by spaces
line_list = clean_line.split(",")
#write 3rd column
if count<160:
target_file.write(line_list[0]+",")
target_file.write(line_list[1]+",")
target_file.write(line_list[2] +"\n")
else if count%160==0:
#Goto first row and next column of the target file and write next 160 lines of 3rd column and continue till the end
count=count+1
# Close Files
input_file.close()
target_file.close()
print("Successfully Generated: \n", file_out_name)
return
if __name__ == "__main__":
if len(sys.argv) != 3:
print ("Invalid input.")
else:
# Parse the USS Template project src input file and store result in
# output csv
decode_file(sys.argv[1], sys.argv[2])
如何每 160 行转到目标文件的第一行和下一列,并从第 3 列写入值。谁能指导我如何做到这一点?
提前致谢。
【问题讨论】:
标签: python csv data-manipulation