Why is my CSV write function not working? This seems to be a very simple code but the CSV writerow
is asking for an iterable. I just need to write the 1,2,3 in a column.
import csv
data = [1,2,3]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
for item in data:
writer.writerow(item)
Gino Mempin
23.1k27 gold badges91 silver badges120 bronze badges
asked Jul 1, 2020 at 2:25
6
You are passing an integer but a list is expected.
import csv
data = [[1],[2],[3]]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
for item in data:
writer.writerow(item)
answered Jul 1, 2020 at 2:47
Joshua LowryJoshua Lowry
1,0453 gold badges11 silver badges30 bronze badges
We need to provide a list to the CSV writer writerow
function, in which there are values for 1 complete row.
e.g
import csv
data = [1,2,3]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
writer.writerow(data) # as data includes only 1 row. For multiple rows write every row with a loop
Gino Mempin
23.1k27 gold badges91 silver badges120 bronze badges
answered Jul 1, 2020 at 3:00
Sohaib AnwaarSohaib Anwaar
1,4771 gold badge11 silver badges28 bronze badges
Я пытаюсь записать список Python в файл csv, используя библиотеки csv
и os
.
Вот что у меня получилось:
from os import path
import csv
import os
example_list=[1,2,3,4,5]
file_path=path.relpath("path")
with open(file_path, mode='w') as f:
list_writer = csv.writer(f, delimiter=',')
for element in example_list:
list_writer.writerow(element)
Однако, когда я открываю его в книге Excel, вывод записывается следующим образом (где каждое горизонтальное пространство представляет новую ячейку):
# 1 2 3 4 5
Я пытаюсь получить ожидаемый результат, который будет выглядеть следующим образом (где каждое вертикальное пространство представляет новую ячейку):
# 1
# 2
# 3
# 4
# 5
Как я могу настроить эту функцию, чтобы получить желаемый результат?
2 ответа
Лучший ответ
Ваш код вызывает следующую ошибку:
_csv.Error: iterable expected, not int
При написании строки вы должны добавить скобки []
вокруг element
, чтобы построить список (который является повторяемым):
list_writer.writerow([element])
Вы также можете заменить цикл for
на:
list_writer.writerow(example_list)
1
joao
19 Фев 2021 в 17:11
Ваш код выдает следующую ошибку _csv.Error: iterable expected, not int
, потому что вам нужно передать итерацию в writerow()
with open(path,'w',newline='') as f:
list_writer = csv.writer(f, delimiter=',')
for element in example_list:
list_writer.writerow([element])
Здесь newline = ''
избегает добавления пробела дополнительной строки
Альтернативный способ использования writerows()
with open(path,'w',newline='') as f:
list_writer = csv.writer(f, delimiter=',')
list_writer.writerows([element] for element in example_list)
0
Midhilesh Momidi
19 Фев 2021 в 18:30
PYTHON — HOW TO FIX «ERROR: ITERABLE EXPECTED, NOT INT» …
Web Jun 30, 2020 We need to provide a list to the CSV writer writerow function, in which there are values for 1 complete row. import csv data = [1,2,3] output = ‘output.csv’ with open (output,’w’) as f: writer = csv.writer (f) writer.writerow (data) # as data includes only 1 …
From stackoverflow.com
Reviews 6
[SOLVED] PYTHON CSV ITERABLE EXPECTED, NOT NONETYPE ISSUE
Web Mar 2, 2022 Mar 2, 2022. #1. cacalun12 Asks: Python csv iterable expected, not NoneType issue. My purpose is have my code read all files in a folder then ouput the …
From solveforum.com
TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE IN PYTHON — STECHIES
Web Thus, integers are not iterable. Conclusion . The presence of the magic method __iter__ is what makes an object iterable. From the above article, we can conclude that. The …
From stechies.com
HELP: ‘INT’ OBJECT IS NOT ITERABLE : R/LEARNPYTHON — REDDIT
Web list.append(tuple(number)) TypeError: ‘int’ object is not iterable Which doesn’t make sense to me because I’m not trying to iterate ‘number’ comments sorted by Best Top New …
From reddit.com
TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE IN PYTHON | BOBBYHADZ
Web The Python TypeError: ‘int’ object is not iterable occurs when we try to iterate over an integer or pass an integer to a built-in function like, `list()` or `tuple()`. To solve the error, …
From bobbyhadz.com
PYTHON — GETTING ‘INT’ OBJECT IS NOT ITERABLE — STACK OVERFLOW
Web cat_sums[cat] += value TypeError: ‘int’ object is not iterable My input is this: … Then the += statement will work as expected. If you cannot change the dictionary but simply want to …
From stackoverflow.com
_CSV.ERROR: ITERABLE EXPECTED, NOT NONETYPE — STACK OVERFLOW
Web May 10, 2022 Since you did not provide machine_scan, I can only guess that it returns None for some cases. writerows expects a list of lists. Either fix machine_scan to always …
From stackoverflow.com
MAKING PYTHON INTEGERS ITERABLE | CODEMENTOR
Web Jun 14, 2020 Since integers, individualistically, are not iterable, when we try to do a for x in 7, it raises an exception stating TypeError: ‘int’ object is not iterable. So what if, we …
From codementor.io
PYTHON WARNING: EXPECTED COLLECTION.ITERABLE, GOT ‘INT’ INSTEAD
Web Jun 14, 2022 Solution 1. The type of some_list_len in your code is Int, so you get the warning. If you want to iterate some_list_len, you can implement by this: some_list_len = …
From 9to5answer.com
FIX PYTHON TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE
Web Jan 5, 2023 To fix this error, add an if statement to ensure that you’re not passing an int when an iterable object is expected. This article will show you how. In Python, an …
From sebhastian.com
WHY IS MY LIST OF NUMBERS NOT AN ITERABLE? : R/LEARNPYTHON — REDDIT
Web It takes the first element of the iterable that you pass and expects to treat that as the first row, but it can’t iterate over an int to get columns. Reply cdcformatc •
From reddit.com
PYTHON TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE SOLUTION
Web Jul 30, 2020 The problem with this line is that we are trying to iterate over a number. len(values) is equal to 4. That’s how many values are in the list “values”. If we try …
From careerkarma.com
HOW TO SOLVE PYTHON “TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE”?
Web TypeError: ‘int’ object is not iterable. But if we pass an iterable object for example a list (even if it consists of one element) to the function then the calculation is successful. a = …
From blog.finxter.com
[SOLVED] TYPEERROR: ‘INT’ OBJECT IS NOT ITERABLE — PYTHON POOL
Web Mar 23, 2022 __iter__ dunder method is a part of every data type that is iterable. In other words, for any data type, iterable only if __iter__ method is contained by them. Let’s …
From pythonpool.com
[SOLVED] PYTHON LIST TO CSV THROWS ERROR: ITERABLE EXPECTED, NOT
Web Jul 23, 2022 Python list to csv throws error: iterable expected, not numpy.int64. You can get this done in many ways. But if you wish to writerows from the csv module, then you …
From 9to5answer.com
INT OBJECT IS NOT ITERABLE – PYTHON ERROR [SOLVED]
Web Mar 24, 2022 How to Fix Int Object is Not Iterable. If you are trying to loop through an integer, you will get this error: count = 14 for i in count: print (i) # Output: TypeError: ‘int’ …
From freecodecamp.org