Python实现向CSV旧索引开头(原有数据上方)追加数据的技术咨询
Hey there! Let's fix that CSV prepend issue you're having. The problem with your current code is that using the 'a' (append) mode always adds content to the end of the file. To put new data at the top, we need to read the existing content first, then write the new stuff followed by the original content.
How to Prepend New Data to a CSV File
First, let's break down the approach:
- Read all existing content from the CSV file
- Construct your new data line
- Overwrite the file by writing the new data first, then appending the original content
Here's the revised, cleaner code that does exactly this:
# Construct your new product line in one go (more concise than multiple writes) new_product_line = f",{introduce_product},{introduce_brand},${introduce_price}\n" # Step 1: Read existing content from the file with open("priv/products.csv", 'r') as file: existing_csv_content = file.read() # Step 2: Write new data first, then the original content with open("priv/products.csv", 'w') as login: login.write(new_product_line) login.write(existing_csv_content)
Quick Notes:
- I used an f-string to combine your four separate
write()calls into one line—it does the exact same job, just with cleaner code. - You don't need to call
login.close()manually when usingwithstatements! Thewithcontext manager automatically handles closing the file once the block finishes, which is safer and more Pythonic. - This works even if the CSV file is empty—
existing_csv_contentwill just be an empty string, so we'll only write the new line.
内容的提问来源于stack exchange,提问作者john eat
相关产品推荐
相关产品推荐

