Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· openaiHugging Face Suzhen/CodeChat

I want to write a python script that reads from and writes to a csv file. The script…

  1. User

    I want to write a python script that reads from and writes to a csv file. The script must output text into every row of specific column by means of a loop and sacve the file every time it is run. What is the simplest way to achieve this?

  2. Assistant

    Here is a simple Python script that reads from a CSV file, writes text into every row of a specific column using a loop, and saves the file every time it is run:

    import csv
    
    # specify the file paths for input and output CSV files
    input_file = "input.csv"
    output_file = "output.csv"
    
    # specify the column where you want to write text
    column_name = "Column2"
    
    # open the input CSV file for reading
    with open(input_file, 'r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        
        # open the output CSV file for writing
        with open(output_file, 'w', newline='') as out_file:
            fieldnames = csv_reader.fieldnames
            writer = csv.DictWriter(out_file, fieldnames=fieldnames)
            
            # write the headers to the output file
            writer.writeheader()
            
            # loop through each row in the input file
            for row in csv_reader:
                # write text into the specified column in each row
                row[column_name] = "Text to write"
                writer.writerow(row)
                
    print(f"Text written to column '{column_name}' in every row.")
    

    All you need to do is replace the values for input_file, output_file, and column_name with your specific file paths and column name. When you run this script, it will read the input CSV file, write "Text to write" into the specified column of each row, and save the updated file as the output CSV file.

  3. User

    Is the csv module included by default in python or do you have to install a package?

  4. Assistant

    The csv module is included in the Python Standard Library, so no additional installation is required to use it. You can simply import the csv module in your Python scripts and start working with CSV files. The csv module provides functionalities to read and write CSV files in a structured way, making it easy to work with tabular data.