How to read any row in a CSV file using Python?
In Python, you can use the csv module to read any line from a CSV file. Here is an example code that demonstrates how to read the 5th and 10th lines from a CSV file.
import csvfilename = 'data.csv' # 替换为你的CSV文件路径
with open(filename, 'r') as file:
reader = csv.reader(file)
rows = list(reader)
row5 = rows[4] # 第5行
row10 = rows[9] # 第10行
print(row5)
print(row10)
Please note that indexing starts at 0, so the index of the 5th row is 4 and the index of the 10th row is 9. In the above code, we first open the CSV file and create a csv.reader object to read the data from the file. Then, we store all the rows in a list. Finally, we use indexes to access specific rows of data. Note: This method is suitable for small CSV files. If the CSV file is very large, it may lead to memory issues. When dealing with large CSV files, it is recommended to use a method that reads line by line.