0

I have a CSV file with only one column. Each row has some words inside.

Hello World1
Hello World2
Hello World3

Now I want to read this file as a list of strings, each row is an item inside the list. Like this:

['Hello World1', 'Hello World2', 'Hello World3']

I have tried below code:

with open("myFile.csv", newline="") as f:
    reader = csv.reader(f)
    data = list(reader)

But it gave me another square brackets inside for each element. How can I remove it?

[['Hello World1'], ['Hello World2'], ['Hello World3']]
xzk
  • 827
  • 2
  • 18
  • 43
  • 1
    you probably want to use `f.readlines()` – luigigi Oct 23 '20 at 08:06
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Wups Oct 23 '20 at 08:06

2 Answers2

4

Solution:
This should solve your use case:

with open('myFile.csv') as file:
    data = file.read().splitlines()

INPUT DATA:

Hello World1
Hello World2
Hello World3

OUTPUT:

['Hello World1', 'Hello World2', 'Hello World3']
Piyush Sambhi
  • 843
  • 4
  • 13
0

If it is a simple text file, you can simply do

with open("myFile.csv") as f:
    data=[line for line in f] 
Dharman
  • 30,962
  • 25
  • 85
  • 135
alexblae
  • 746
  • 1
  • 5
  • 13