python transform script to reading CSV files from folder , read only lines containing…
- User
python
transform script to reading CSV files from folder , read only lines containing
import pandas as pd import zipfile from pathlib import Path
def merge_zip_csv_files(folder_path): # Create an empty DataFrame to store the merged data merged_df = pd.DataFrame()
# Iterate through each zip file in the folder for zip_file in Path(folder_path).glob("*.zip"): with zipfile.ZipFile(zip_file, 'r') as z: # Assume there is only one file named 'result.csv' in each zip for name in z.namelist(): if name.endswith('results.csv'): # Read the CSV file from the zip into a DataFrame df = pd.read_csv(z.open(name) , skip_blank_lines=True , on_bad_lines='skip' ) df = df[df['base_domain']. isin(['avito.ru'])] # Append the data to the merged DataFrame merged_df = pd.concat([merged_df, df], ignore_index=True) return merged_dfExample usage:
folder_path = "D:/Теги/homeliving/" result_df = merge_zip_csv_files(folder_path) display(result_df)
- Assistant
To modify the given script so that it reads CSV files directly from a folder and only processes lines containing a specific URL (e.g., "avito.ru"), we can adjust the logic as follows:
- Loop through
.csvfiles in a specified folder instead of.zipfiles. - Check each row for the presence of the desired URL before adding it to the DataFrame.
Below is a revised version of your Python script:
- Loop through