Допустим, ваш входной файл .csv
выглядит следующим образом:
Address
8519-21 S Broadway
8700-6 Riverview Blvd
822-4 Angelica St
8442-6 N Broadway
, и вы хотите, чтобы он выглядел примерно так:
First Address,Last Address
8519 S Broadway,8521 S Broadway
8700 Riverview Blvd,8706 Riverview Blvd
822 Angelica St,824 Angelica St
8442 N Broadway,8446 N Broadway
Вы можете сделать это, используяcsv
модуль:
from csv import writer
# open both input and output csv
with open("addresses.csv") as csv_in, open("output.csv", "w", newline="") as csv_out:
csv_writer = writer(csv_out)
# Skip 'Address' header
next(csv_in)
# Write new headers
csv_writer.writerow(["First Address", "Last Address"])
# Go through each line in csv
for line in csv_in:
# Split ranges from rest of line
ranges, *rest = line.split()
# Split ranges themselves
start, end = ranges.split("-")
# Get difference between length of numbers
diff = len(start) - len(end)
# Create new end address
end = start[:diff] + end
# Write new lines to output csv
csv_writer.writerow([" ".join([start, *rest]), " ".join([end, *rest])])
, который выведет ваши результаты в output.csv .