我有两个文件。
file1:
0,1,2,3,4,5,6,7,8,9,7585,10,11
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20
0,1,2,3,4,5,6,7,8,9,10,11
file2:
0,1,2,3,4,5
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15,16,17,18
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20,21,22
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14
我试图导出所有的行,其中索引10 ==7585
到Excel,
这是我的代码
my_path = r'c:dataEKLDesktopmy-files'
for file in os.listdir(my_path):
path_file = os.path.join(my_path, file)
with open(path_file, 'r') as output:
reader = csv.reader(output, delimiter = ',')
read = [row for row in reader if row]
for row in read:
if row[10] == '7585':
print(','.join(row[0:]))
这是我的结果:
Traceback (most recent call last):
File "C:dataEKLDesktopPythonPythongMySQLuntitled2.py", line 14, in <module>
if row[10] == '7585':
IndexError: list index out of range
这是我在EXCEL工作表中期望的结果:
0,1,2,3,4,5,6,7,8,9,7585,10,11
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15,16,17,18
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20,21,22
这对我有用:
import os
import csv
my_path = r'sof' # local path of csv files
index = 10 # index you would like to check
value = '7585' # value of the index it should be
for file in os.listdir(my_path):
path_file = os.path.join(my_path, file)
with open(path_file, 'r') as output:
reader = csv.reader(output, delimiter = ',')
read = [row for row in reader if row]
for row in read:
if len(row) >= index and row[index] == value:
print(','.join(row[0:]))
输出0,1,2,3,4,5,6,7,8,9,7585,10,11
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,14,15,16,17,18
0,1,2,3,4,5,6,7,8,9,7585,10,11,12,13,14,15,16,17,18,19,20,21,22
更新-使用Excel导出
import os
import csv
import xlsxwriter
my_path = r'sof'
index = 10
value = '7585'
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first row
rown = 0
for file in os.listdir(my_path):
path_file = os.path.join(my_path, file)
with open(path_file, 'r') as output:
reader = csv.reader(output, delimiter = ',')
read = [row for row in reader if row]
for row in read:
if len(row) >= index and row[index] == value:
worksheet.write_row("A"+str(rown+1),row)
rown+=1
workbook.close()
没有检查它是否正在运行,但我会尝试这样做:
my_path = r'c:dataEKLDesktopmy-files'
for file in os.listdir(my_path):
path_file = os.path.join(my_path, file)
with open(path_file, 'r') as output:
reader = csv.reader(output, delimiter = ',')
read = [row for row in reader if row]
for row in read:
if (len(row) > 10) and (row[10] == '7585'): # add extra condition
print(','.join(row[0:]))