python读写txt文件、csv文件

本文介绍了如何使用Python进行TXT和CSV文件的读写操作。通过`open`函数的读取模式读取TXT文件,利用for循环遍历每一行。在写入方面,采用 wb 模式,并使用 `writerow` 和 `writerows` 方法来写入一行或多行数据到CSV文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值