首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

#cvs

文件CSV中每一行中间的空格

成品冻K感情是人一辈子也捉摸不透的东西
已采纳
你的问题是,csv-模块writerows有自己的“换行符”-逻辑。它会干扰默认的换行符行为。open(): 像这样修正: with open('rutasAeropuertos.csv', 'w', newline='' ) as archivo_rutas: # ^^^^^^^^^^ 在文档中的示例中也记录了这一点 如果csv文件是一个文件对象,应该用newline='' 有一个脚注的链接告诉你: 一如果未指定newline=‘,则嵌入在引号字段中的换行符将无法正确解释,并且在使用\r\n写一个额外的行\r将被添加。指定newline=‘应该是安全的,因为CSV模块执行自己的(通用)换行符处理。 使用的是windows,它确实使用\r\n这会增加另一个\r,从而导致“错误”输出。 包含一些优化的完整代码: import csv import random def dict_ID_aeropuertos(): with open('AeropuertosArg.csv') as archivo_csv: leer = csv.reader(archivo_csv) dic_ID = {} for linea in leer: dic_ID.setdefault(linea[0],linea[1]) return dic_ID def ruteoAleatorio(): dic_ID = dict_ID_aeropuertos() lista_ID = list(dic_ID.keys()) lista_rutas = set() # a set only holds unique values while (len(lista_rutas) < 50): # simply check the length of the set r1,r2 = random.sample(lista_ID, k=2) # draw 2 different ones lista_rutas.add( (r1,r2) ) # you can not add duplicates, no need to check with open('rutasAeropuertos.csv', 'w', newline='' ) as archivo_rutas: escribir = csv.writer(archivo_rutas) escribir.writerows(lista_rutas) ruteoAleatorio() 产出: 9,3 16,10 15,6 [snipp lots of values] 13,14 13,7 20,4... 展开详请
你的问题是,csv-模块writerows有自己的“换行符”-逻辑。它会干扰默认的换行符行为。open(): 像这样修正: with open('rutasAeropuertos.csv', 'w', newline='' ) as archivo_rutas: # ^^^^^^^^^^ 在文档中的示例中也记录了这一点 如果csv文件是一个文件对象,应该用newline='' 有一个脚注的链接告诉你: 一如果未指定newline=‘,则嵌入在引号字段中的换行符将无法正确解释,并且在使用\r\n写一个额外的行\r将被添加。指定newline=‘应该是安全的,因为CSV模块执行自己的(通用)换行符处理。 使用的是windows,它确实使用\r\n这会增加另一个\r,从而导致“错误”输出。 包含一些优化的完整代码: import csv import random def dict_ID_aeropuertos(): with open('AeropuertosArg.csv') as archivo_csv: leer = csv.reader(archivo_csv) dic_ID = {} for linea in leer: dic_ID.setdefault(linea[0],linea[1]) return dic_ID def ruteoAleatorio(): dic_ID = dict_ID_aeropuertos() lista_ID = list(dic_ID.keys()) lista_rutas = set() # a set only holds unique values while (len(lista_rutas) < 50): # simply check the length of the set r1,r2 = random.sample(lista_ID, k=2) # draw 2 different ones lista_rutas.add( (r1,r2) ) # you can not add duplicates, no need to check with open('rutasAeropuertos.csv', 'w', newline='' ) as archivo_rutas: escribir = csv.writer(archivo_rutas) escribir.writerows(lista_rutas) ruteoAleatorio() 产出: 9,3 16,10 15,6 [snipp lots of values] 13,14 13,7 20,4
领券