Importing .csv values as single list in Python
Try the following code
import csv
results = []
with open('test.csv', newline='') as inputfile:
for row in csv.reader(inputfile):
results.append(row[0])
print(results)
How do I read CSV files and put it in list with Python?
You are using this:
customerID += item[0]
But that doesn't do what you think it does. customerID
is a list and you're using the add operator on it, so Python tries to interpret item[0]
as a list as well, which is a str
, but can be considered a list of characters - so that's exactly what gets added.
Instead, use:
customerID.append(item[0])
Or, if you prefer:
customerID += [item[0]]
How to import a CSV data to a single list and append some values to the same?
Use chain.from_iterables
from itertools
:
import itertools
mylist = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
mylist = list(itertools.chain.from_iterable(mylist))
mylist.append('hello')
>>> mylist
['1', '2', '3', '4', '5', '6', '7', '8', 'hello']
Writing a whole list into one row in csv python
First off, try not to name your variables the same as builtin types (list). This can break lots of stuff.
Edit: nvm I saw you edited your post.
You can just merge the list and variable into a string and then write that. You don't even need the csv writer.
myList = [a,b,c,d]
with open("CSVfile" + '.csv','w', encoding='utf-8') as f:
line = '\t'.join([myVariable] + myList)
f.write(line + '\n')
Importing CSV-file as list returns empty list
This is because a variable declared inside a function is only available inside that function and not in the global scope. In this case my suggestion would be to return the data from the function after you have finished reading the file. In other words something like this:
import csv
def read_file():
with open ('filepath', 'r') as file:
csv_reader = csv.reader(file, delimiter=';')
data=[]
for rad in csv_reader:
data.append(rad)
return data
file_data = read_file()
print(file_data)
It is also possible to make the data
variable inside the function global, however this is normally not recommended due to global variables quickly becoming hard to keep track of, it is much easier to see where data is coming from when it is returned from a function like this.
Related Topics
How to Convert Index of a Pandas Dataframe into a Column
Single Quotes Vs. Double Quotes in Python
Pipe Raw Opencv Images to Ffmpeg
Pip Is Not Working for Python 3.10 on Ubuntu
"Valueerror: _Type_ 'V' Not Supported" Error After Installing Pyreadline
Capturing Output of Python Script Run Inside a Docker Container
Auto Executable Python File Without Opening from Terminal
Find the Similarity Metric Between Two Strings
Python Gdal 2.1 Installation on Ubuntu 16.04
Setting Ld_Library_Path from Inside Python
How to Make Python Script Press 'Enter' When Prompted on Shell
Finding the Command for a Specific Pid in Linux from Python
Cannot "Pip Install Cryptography" in Docker Alpine Linux 3.3 with Openssl 1.0.2G and Python 2.7