1. text读写
(1)读
stopwords = {}.fromkeys([line.rstrip() for line in open('./data/stopwords.txt')])
for line in open("./feature/ntusd-negative.txt"):
(2)写
fou=open('.
/data/wiki_newwords.txt','w')
fou.write(str_out)
file_object = open('./data/wiki_newwords.txt', 'w')
file_object.writelines(ss)
2. csv读写
(1) csv读
csvfile = file('csv_test.csv', 'rb')
reader = csv.reader(csvfile)
for line in reader:
for temp in line:
print temp.decode('gb2312')
csvfile.close()
(2) csv写入 中文正确写入
#encoding=utf-8
import csv
csvfile = file('csv_test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(['姓名'.decode('utf-8').encode('gb2312')
, '年龄'.decode('utf-8').encode('gb2312')
, '电话'.decode('utf-8').encode('gb2312')
])
data = [
('小河'.decode('utf-8').encode('gb2312')
, '25', '1234567'),
('小芳'.decode('utf-8').encode('gb2312')
, '18', '789456')
]
writer.writerows(data)
csvfile.close()
- wb中的w表示写入模式,b是文件模式
- 写入一行用writerow
- 多行用writerows