有谁知道如何解决这个问题。我正在检查偶数行中是否有“1850年人口普查”这一短语。如果它在该行中找到该短语,则应保留该行及其上一行。如果没有找到,则应删除该行及其上一行。我使用的数据集是:
(didn't粘贴在其他行,但还有更多)
我使用的代码是:
import csv
def scan_csv_file(file_path):
"""
This function scans a CSV file and performs the following operations:
- Scans the even rows for the phrase "Census 1850" anywhere in the row
- If found, keeps that cell and deletes the cell above it
- If not found, deletes that row and one row above it
- Checks only the even rows for this
Parameters:
file_path (str): The path to the CSV file to be scanned
Returns:
None
"""
try:
# Open the CSV file
with open(file_path, 'r') as file:
# Read the CSV file
csv_reader = csv.reader(file)
# Create a list to store the rows to be written to a new file
new_rows = []
# Create a variable to keep track of the current row number
row_num = 0
# Initialize the new_row variable outside the loop
new_row = []
# Loop through each row in the CSV file
for row in csv_reader:
# Check if the row number is even
if row_num % 2 == 0:
# Check if the phrase "Census 1850" is in the row
if "Census 1850" in ','.join(row):
# Keep the current cell and delete the cell above it
new_row = row[1:]
else:
# Delete the current row and the row above it
if len(new_rows) > 0:
new_rows.pop()
continue
else:
# Keep the current row
new_row = row
# Append the new row to the list of rows
new_rows.append(new_row)
# Increment the row number
row_num += 1
# Overwrite the existing CSV file with the new rows
with open(file_path, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(new_rows)
print("CSV file modified successfully.")
except Exception as e:
# Log the error
print(f"Error: {e}")
# Provide the path to your CSV file
file_path = r"C:\Users\My Name\Downloads\tracing_the_land_2_test.csv"
scan_csv_file(file_path)
但是,它只是不断地删除文档中的所有内容。有人能帮我吗?
1条答案
按热度按时间e4yzc0pl1#
你pop()不包含你正在搜索的语句的行,因此你的总行数会改变,你访问每行的顺序也会改变。换句话说,您不必访问每一行。让我给予你一个场景:在你的代码的开始你的文件有8行,当你开始你检查rows_number 2并弹出上面的行。之后,您的文件将有6行,您将访问新文件的rows_number 4,这是您以前文件的row_number 6。以这种方式跳过一些行。希望对你有帮助。