Last active
December 7, 2018 07:46
-
-
Save cakoose/f7140eb10a7dc0088d1482f1801a3542 to your computer and use it in GitHub Desktop.
Handling CSV column reordering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Last | First | Age | |
---|---|---|---|
Doo | Scooby | 12 | |
Macdonald | Norm | 50 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Gender | Last | Age | First | |
---|---|---|---|---|
M | Doo | 12 | Scooby | |
M | Macdonald | 50 | Norm |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import csv | |
assert sys.version_info > (3, 2), ( | |
"This program requires Python 3.2+. " | |
"You're trying to run it with Python {}.".format('.'.join(map(str, sys.version_info[:3])))) | |
def main(): | |
args = sys.argv[1:] | |
if len(args) != 1: | |
sys.stderr.write("Error: expecting exactly one argument, got {!r}.\n".format(args)) | |
raise sys.exit(1) | |
with open(args[0], encoding='utf8') as f: | |
reader = csv.reader(f) | |
actual_headers = next(reader) | |
desired_headers = ['First', 'Last', 'Age'] | |
# TODO: Using 'actual_headers' and 'desired_headers', come up with a mapping | |
# so that we know: for each desired_header, what is its actual index. | |
for row in reader: | |
# TODO: Using the mapping calculated above, extract the three desired values from row. | |
(first, last, age) = ('?', '?', '?') | |
print('First', first, 'Last', last, 'Age', age) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment