lst = [[1-1,1-2,1-3], [2-1,2-2,2-3], [3-1,3-2,3-3] ]
I would like to output the above list to csv as below.
1-1,1-2,1-3 2-1,2-2,2-3 3-1,3-2,3-3
For this reason, if you write code like the one below, the line breaks one by one.
import csv lst = [[1-1,1-2,1-3], [2-1,2-2,2-3], [3-1,3-2,3-3]] for i in range (len (lst)): for j in range (len (lst [i])): with open ('D: \\ Desktop \\ test_aaa.csv', 'a', newline = '') as f: writer = csv.writer (f) writer.writerow ([lst [i] [j]])
output 1-1 1-2 1-3 2-1 2-2 2-3 3-1 3-2 3-2
How can I prevent line breaks from occurring one by one?
Answer # 1
writerow literally outputs a line.
Also, it is usually useless to reopen the file every week in append mode.
with open (r'D: \ Desktop \ test_aaa.csv ',' w ', newline =' ') as fout: writer = csv.writer (fout) for row in lst: writer.writerow (row)
Actually, you can output at once with writerows.
with open (r'D: \ Desktop \ test_aaa.csv ',' w ', newline =' ') as fout: writer = csv.writer (fout) writer.writerows (lst)
There are other corrections, so please compare them.
- python - histogram is not standardized despite writing density=true
- python - how to avoid errors when using ctypes pointers
- python - writing when the tcp socket network buffer is full
- [error when writing to csv file] unicodeencodeerror [python]
- python 3x - question when writing dataframe to excel file
- when writing a yaml file read by python, i want to prevent the value from being changed
- python 3x - to change the date format when writing a data frame
- python - the first step in writing function code
- python - backslashes reduced when writing full path to ini file
- python csv writing
- python - i want to avoid "no response" when pressing gui button in pyqt
- python - when writing to a file and then reading, the strings are linked and printed
- python - how to remove a list from a tuple and store only the value
- http error 503: service unavailable when doing amazon scraping with python
- python - i want to simplify the program that sequentially retrieves from the list
- python - regarding the problem that tries to decompose a string apostrophe using a dictionary but fails
- python - common behavior for everything in django
- python - i want to split one array into two without duplication
- about the problem that float subtraction does not work in numerical calculation in python
- python - something went wrong in the jupiter lab
- python - how to deal with error when converting pandas datetime type
- i want to read python time series data while shifting by 1 day