In this tutorial, we will learn how to append a timestamp to a CSV file using Python. Using Python to append a timestamp to a CSV file can prove to be very useful for tracking data changes over time.
We will first load the CSV file using the Pandas python library, add the timestamp column, and then save the updated CSV file.
Step 1: Install Required Libraries
To work with CSV files, we need to have the Pandas library installed. If you have not done so already, you can install it by running the below command in your terminal:
1 |
pip install pandas |
Step 2: Import Required Libraries
After installing the required library, the next step is to import it. We will also import the datetime module to generate the timestamp:
1 2 |
import pandas as pd from datetime import datetime |
Step 3: Load the CSV file
To load the CSV file, we use the read_csv function from the Pandas library:
1 |
data = pd.read_csv('file.csv') |
Step 4: Add the Timestamp
Next, we will add a new column to our dataframe with the current timestamp. Let’s call this column ‘Timestamp’:
1 |
data['Timestamp'] = datetime.now() |
Step 5: Save the CSV File
Lastly, we will save the updated dataframe to a new CSV file:
1 |
data.to_csv('updated_file.csv', index=False) |
Full Code
1 2 3 4 5 6 |
import pandas as pd from datetime import datetime data = pd.read_csv('file.csv') data['Timestamp'] = datetime.now() data.to_csv('updated_file.csv', index=False) |
Conclusion
To conclude, appending the timestamp to a CSV file in Python is quite easy. We just need to load the CSV file, add a new column for the timestamp, and then save the updated dataframe to a new CSV file.
The whole process only requires a few lines of code with the help of the powerful Pandas library.