fw.write(list2)
TypeError: write() argument must be str, not list
类型转换:str转list与list转str
test_str = "".join(test_list) #使用分割
TypeError: sequence item 0: expected str instance, int found
tr2 = ",".join(str(x) for x in list2)+'\n'
至此,上述问题解决***************************************************************************************
对csv文件操作小结
读csv文件
with open('D:/trace analyse/a.csv','rt', encoding="utf-8") as csvfile:
reader=csv.reader(csvfile)
next(csvfile)#跳过第一行
for raw inreader:#对每一行处理
csvfile.close()
写csv文件
with open('D:/trace analyse/b.csv','w+',newline='') as wfile:
writer=csv.writer(wfile)for key indict:for value indict[key]:
writer.writerow([key, value, dict1.get(key+value)])
wfile.close()
当csv文件没有标题行的时候,对csv的读取可以添加
train = pd.read_csv(file, header=None, names = ['a','b','c'] )
将ndarray写入csv文件
pd_data = pd.DataFrame(np_data,columns=['filename','gender'])pd_data.to_csv('pd_data.csv')
在一个csv每行末尾添加一列
with open(file,'rt', encoding="utf-8") as csvfile:
reader=csv.reader(csvfile)
next(csvfile)
writefile= open(file,'w+',newline='')
writer=csv.writer(writefile)for raw inreader:if raw[0] indict:
raw.append(dict[raw[0]])
writer.writerow(raw)
csvfile.close()
writefile.close()
***************************************************************************************
对txt文件操作小结
fw = open('D:/trace analyse/cputime-serires.txt','a')
fw.write(str2)#这里不能写list类型
fw.close()
fr = open('D:/trace analyse/cputime-serires.txt','r') #按行读取数据
for str1 in fr.readlines():
***************************************************************************************
Random使用
random.randint(0,max) #产生一个0-max的整数
***************************************************************************************
List操作
求list全部元素的总和
sum(list2) #求list2全部元素的总和
对list中的元素执行统一操作
defSubmethod(value):if value >= 1:
value-= 1
returnvalue
list2= list(map(Submethod,list2))
这种map方式,map中的function没法传递两个参数
map(square, list) #内置函数,对list每个元素求平方
map(lambda x: x ** 2, list) #自定义函数,同样是求平方
map(lambda x, y: x + y, list1, list2) #自定义函数,对两个list操作
这种map方式,对于条件语句不友好
***************************************************************************************