在Python中编写CSV文件名和行数可以通过以下步骤实现:
import csv
csv.writer
函数创建一个CSV文件对象,并使用writerow
方法将数据写入CSV文件中。with open('filename.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John', '25', 'New York'])
writer.writerow(['Alice', '30', 'London'])
csv.reader
函数打开CSV文件,并使用len
函数获取行数。with open('filename.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
csv_data = list(reader)
num_rows = len(csv_data)
file_name = csvfile.name
完整代码示例:
import csv
# 创建CSV文件并写入数据
with open('filename.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John', '25', 'New York'])
writer.writerow(['Alice', '30', 'London'])
# 获取CSV文件名和行数
with open('filename.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
csv_data = list(reader)
num_rows = len(csv_data)
file_name = csvfile.name
print("CSV文件名:", file_name)
print("行数:", num_rows)
请注意,以上代码示例仅为演示如何在Python中编写CSV文件名和行数,实际应用中可能需要根据具体需求进行适当修改。
领取专属 10元无门槛券
手把手带您无忧上云