I'm trying to learn Python but I'm stuck here, any help appreciated.
I have 2 files.
1 is a .dat file with no column headers that is fixed width containing multiple rows of data 1 is a .fmt file that contains the column headers, column length, and datatype
.dat example:
10IFKDHGHS34
12IFKDHGHH35
53IFHDHGDF33
.fmt example:
ID,2,n
NAME,8,c
CODE,2,n
Desired Output as .csv:
ID,NAME,CODE
10,IFKDHGHS,34
12,IFKDHGHH,35
53,IFHDHGDF,33
First, I'd parse the format file.
with open("format_file.fmt") as f:
# csv.reader parses away the commas for us
# and we get rows as nice lists
reader = csv.reader(f)
# this will give us a list of lists that looks like
# [["ID", "2", "n"], ...]
row_definitions = list(reader)
# iterate and just unpack the headers
# this gives us ["ID", "NAME", "CODE"]
header = [name for name, length, dtype in row_definitions]
# [2, 8, 2]
lengths = [int(length) for name, length, dtype in row_definitions]
# define a generator (possibly as a closure) that simply slices
# into the string bit by bit -- this yields, for example, first
# characters 0 - 2, then characters 2 - 10, then 8 - 12
def parse_line(line):
start = 0
for length in lengths:
yield line[start: start+length]
start = start + length
with open(data_file) as f:
# iterating over a file pointer gives us each line separately
# we call list on each use of parse_line to force the generator to a list
parsed_lines = [list(parse_line(line)) for line in data_file]
# prepend the header
table = [header] + parsed_lines
# use the csv module again to easily output to csv
with open("my_output_file.csv", 'w') as f:
writer = csv.writer(f)
writer.writerows(table)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.