各种文件的写入

例子 读取一个后缀为.featnames的文件,创建一个0featnames.txt的文件 并将0.featnames文件的内容写入

1
2
3
4
5
file_name = '0.featnames'
file = open(r'0featnames.txt',mode = 'w')
with open(file_name,'r') as f:
for line_t in f:
file.write(line_t)

上面那个例子存在BUG,会将一行中所有的数据写入一个单元格,所以更改例子如下:

1
2
3
4
5
6
7
8
9
import csv

# attention! 设置newline,否则会出现两行之间有一行空行
with open('test2.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
data = open('0circles.txt') # 改成自己的路径
for each_line in data:
a = each_line.split() #我的数据每行都是字符串,所以将str按空格分割,变成list
writer.writerow(a)

此时完美解决

2020-7-1 更新

出现空行的原因各个版本的open函数不一样