Guide to CSV File Handling with Python Script Examples
School
Tri-Village**We aren't endorsed by this school
Course
MATHAMATICS 11TH
Subject
Computer Science
Date
Dec 12, 2024
Pages
2
Uploaded by xunanglao02
bl bl ' iy o : = p sys with open(input_file, , newline='') as filereacer: with open(output_file, ‘w', newline='') as filewriter header = fllereader.readline() header = header.s pl) hea = header.split( ) R T der_list) S— ax sriter.urite Join(map(ster,header_list))= ) e for row in filereader; £ y (') 1 pri . fllewriter.uritel Jotn(map(ste,row_11st) )+ ) we p P Figure 2-3. The lcsv_read_with_simple_parsing_and_write.py Python script-in Ana- conda Spyder | import sys ) as filereader: we="1 as filewriter: ' | | filewriter.write(', ".join(map (str,row list))+ ) | Figure 2-4. The lcsv_read_with_simple_parsing_and_write.py Python script in Notepad ++ (Windows) Base Python Versuspandas | 63
® oy S g » s c.m, 4, #!/usr/bin/env python3 import sys input_file = sys.argv[1] output_file = sys.argv[2] * with open(input_file, ', newline=") as filereader: with open(output_file, 'w', newline=") as filewriter: header = filereader.readling() header = header.strip() %, header_list = header.split(’,") print(header_list) filewriter.write(’,". join(map(str,header_list))+\n’) for row in filereader: row = row.strip() row_list = row.split(',') print(row_list) filewriter.write('," join(map(str,row_list))+n’) Pynon’ § Unicode IUTF-8 4 Usi P ¢ o Lastsowec SRUIK I00Ge8 AN | [ 9527102/ 18 Figure 2-5. The 1csv_read_with_simple_parsing_and_write.py Python script in Text- Wrangler (macOS) Before we run this script and view the output, let’s explore what the code in the script is supposed to do. We'll discuss each of the blocks of code in turn (the line numbers refer to the line numbers shown in the screenshots): #!/usr/bin/env python3 import.sys As we discussed in Chapter 1, line 1 is a comment line that makes the script transfer- able across operating systems. Line 2 imports Python’s built-in sys module, which enables you to send additional input to your script from the command line. input_file = sys.argv[1] output_file = sys.argv[2] Lines 4 and 5 use the sys module’s argv parameter, which is the list of command-line arguments passed to a Python script—that is, what you enter at the command line at the time you run the script. Here is a generic version of the command-line arguments we'll use to read a CSV input file and write a CSV output file on a Windows com- puter: python script_name.py "C:\path\to\input_file.csv" "C:\path\to\output_file.csv" The first word, python, tells your computer to use the Python program to process the rest of the command-line arguments. Python collects the rest of the arguments into a 64 | Chapter 2: Comma-Separated Values (CSV) Files