我有一个CSV数据列表,如下所示:
Jim 57 83 55 78
John 98 91 80
Michael 61 88 80 60
Harry 92 58 50 57
James 51 97 52 53
我希望在没有导入CSV模块的情况下返回,我想要打印的空白值无,并且在名称周围加双引号,并且没有整数引号:
[("Jim",57,None,83,55,78), ("John",None,98,91,80,None), ("Michael",61,None,88,80,60)]....
我尝试了一些代码:
def student_mark(studentfile):
f = open (studentfile, 'r')
list = []
for line in f:
list.append(tuple(line.strip().split(',')))
print (list)
studentfile = " users/.../units.csv"
student_mark(studentfile)
但现在结果如下:
[('Jim','57','','83','55','78'), ('John','','98','91','80',''), ('Michael','61','','88','80','60')
任何人都可以帮助我吗?
答案 0 :(得分:0)
关键是使用str.isdigit()。判断字符串是否为数字,这个答案可以帮助你吗?
import csv
filepath = r'C:\Users\kudangren\Desktop\testfile\testfile.csv'
def CleanData(line):
listline = []
for i in line:
if i.isdigit():
listline.append(int(i))
elif i == '':
i = 'None'
listline.append(i)
else:
listline.append(i)
return tuple(listline)
def student_mark(studentfile):
with open(studentfile,'r') as csvfile:
read = csv.reader(csvfile)
resultlist = []
for line in read:
resultline=CleanData(line)
resultlist.append(resultline)
print(resultlist)
student_mark(filepath)
答案 1 :(得分:0)
以下是我重建的代码:
filepath = r'C:\Users\kudangren\Desktop\testfile\testfile.csv'
def CleanData(line):
listline = []
for i in line:
if i.isdigit():
listline.append(int(i))
elif i == '':
i = 'None'
listline.append(i)
else:
listline.append(i)
return tuple(listline)
def student_mark(studentfile):
with open(studentfile,'r') as csvfile:
read = csvfile.read()
resultlist = []
for line in read.split('\n'):
result=CleanData(line.split(','))
resultlist.append(result)
print(resultlist)
student_mark(filepath)
执行结果:
[('Jim', 57, 'None', 83, 55, 78), ('John', 'None', 98, 91, 80, 'None'), ('Michael', 61, 'None', 88, 80, 60), ('Harry', 92, 'None', 58, 50, 57), ('James', 51, 'None', 97, 52, 53)]