Python escribir en CSV línea por línea
Tengo datos a los que se accede a través de una solicitud http y que el servidor envía de vuelta en un formato separado por comas, tengo el siguiente código:
site= 'www.example.com'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)
El contenido del texto es el siguiente:
april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9
¿Cómo puedo guardar estos datos en un archivo CSV. Sé que puedo hacer algo a lo largo de las líneas de lo siguiente para iterar línea por línea:
import StringIO
s = StringIO.StringIO(text)
for line in s:
Pero no estoy seguro de cómo escribir correctamente cada línea en CSV
EDITAR - - - > Gracias por los comentarios como se sugirió la solución fue bastante simple y se puede ver a continuación.
Solución:
import StringIO
s = StringIO.StringIO(text)
with open('fileName.csv', 'w') as f:
for line in s:
f.write(line)
4 answers
Vía general:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
for line in text:
file.write(line)
file.write('\n')
O
Usando CSV writer:
import csv
with open(<path to output_csv>, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
O
La forma más sencilla:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-18 04:05:33
Simplemente podría escribir en el archivo como escribiría cualquier archivo normal.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
Si por si acaso, es una lista de listas, podría usar directamente el módulo incorporado csv
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-18 03:59:14
Simplemente escribiría cada línea en un archivo, ya que ya está en formato CSV:
write_file = "output.csv"
with open(write_file, "w") as output:
for line in text:
output.write(line + '\n')
No puedo recordar cómo escribir líneas con saltos de línea en este momento, sin embargo: p
También te gustaría echar un vistazo a esta respuesta acerca de write()
, writelines()
, y '\n'
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:27
¿Qué hay de esto:
with open("your_csv_file.csv", "w") as f:
f.write("\n".join(text))
Str.join () Devuelve una cadena que es la concatenación de las cadenas en iterable. El separador entre elementos es la cadena que proporciona este método.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 20:43:16