我必须将包含在csv文件列中的代码写入新文件(从每行)。当然,代码实际上应该包含换行符,所以我插入了一个占位符字符(@),在输出新文件时,我想将它转换为换行符。我试着在代码中的不同位置做一个替换,但是没有任何效果。我甚至没有用\r\n字符串替换@。在我的上一个版本(下面)中,python很高兴地继续输出@:
import csv
import codecs
tablelist=('gz_categoria', 'gz_cabildo')
counter=0
for item in tablelist:
with open('C:/Hgis/'+"%s" % (item)+'.csv', 'r') as csvFile:
reader = csv.reader(csvFile)
for row in reader:
row[1].replace('\r\n', '\\r\n')
row[1].replace('@', '\\r\n')
newpage = codecs.open ('C:/Hgis/db/'+"%s" % (item)+''+str(counter)+'.txt',encoding='utf-8', mode='w+')
newpage.write(row[1].decode('UTF-8'))
counter = counter+1
newpage.close()以下是csv的前两行:
1,-数据条目分类-@ID:1000135分类:Ciudad@exact de:@Desde: 1539@Hasta: 9999@Desde_fuzzy: exact@Hasta_fuzzy: end@--,1000135,Patzcuaro,1539,确切,9999,end,Ciudad,Ciudad,gerhardNE,无,No,-2
2,-数据条目分类-@ID:1000136分类法: Pueblo@subcategoria: Pueblo de indios@es parte de:@Desde: 1111@Hasta: 9999@Desde_fuzzy: start@Hasta_fuzzy: end@-,1000136,Puruandiro,1111,start,9999,end,Pueblo,Pueblo de indios,tanck,0,No,0
文件1中的期望输出:
-数据条目分类
ID: 1000135
类别: Ciudad
次分类: Ciudad
埃斯帕特:
德雷德: 1539
哈斯塔: 9999
Desde_fuzzy:确切
Hasta_fuzzy:结束
发布于 2019-03-03 17:57:05
事实上,正如@snakecharmerb所评论的,错误并没有为结果分配变量:
以下代码产生所需的结果:
tablelist=('gz_categoria', 'gz_cabildo')
counter=0
for item in tablelist:
with open('C:/Hgis/'+"%s" % (item)+'.csv', 'r') as csvFile:
reader = csv.reader(csvFile)
for row in reader:
row[1].replace('@', '\r\n')
newpage = codecs.open ('C:/Hgis/db/'+"%s" % (item)+''+str(counter)+'.txt',encoding='utf-8', mode='w+')
newpage.write(row[1].decode('UTF-8'))
counter = counter+1
newpage.close()https://stackoverflow.com/questions/54971255
复制相似问题