Created
May 31, 2024 07:35
-
-
Save sonnguyen9800/e9b46198692ed946fc9e199dd091a340 to your computer and use it in GitHub Desktop.
Tool_ParseCSV.py
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 csv | |
def filter_and_print_columns(filename, column_names, filename_output): | |
""" | |
This function reads a CSV file, filters and prints data from specified columns. | |
Args: | |
filename: The path to the CSV file. | |
column_names: A list of column names to print data from. | |
""" | |
formatted_data = [] | |
# Open the CSV file | |
with open(filename, 'r', encoding='utf-8-sig') as csvfile, open(filename_output, 'w', newline='') as outfile: | |
csv_reader = csv.reader(csvfile) | |
csv_writer = csv.writer(outfile) | |
# Identify column indices (assuming headers are present) | |
header = next(csv_reader) | |
print(header) | |
column_indices = [header.index(name) for name in column_names if name in header] | |
# Check if all columns exist | |
if len(column_indices) != len(column_names): | |
missing_columns = set(column_names) - set(header) | |
print(f"Columns {', '.join(missing_columns)} not found in the CSV file.") | |
return | |
# Iterate through rows and print specified columns | |
for row in csv_reader: | |
filtered_data = [row[i] for i in column_indices] | |
#print(filtered_data) | |
formatted_string = "" | |
for (name, value) in zip(columns_name_code, filtered_data): | |
if (value != None and value != 0 and value != ""): | |
#print(name, value) | |
formatted_string += (f"{name}:{value};") | |
formatted_data.append(formatted_string) | |
final_string = formatted_string | |
outfile.write(''.join(final_string)) | |
outfile.write('\n') # Add a newline character after each row | |
# Example usage | |
filename = 'Input.csv' | |
column_names = ['Coin', "UnlimitedLives", "TileUndo", "TileWand", "TileShuffle", "TileExtraSlot", "TileRetract"] # Replace with your desired column names | |
columns_name_code = ['CO', 'UnlimitedLives', 'TileUndo', 'TileWand', 'TileShuffle', 'TileExtraSlot', 'TileRetract'] | |
filter_and_print_columns(filename, column_names, "output.csv") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment