For example this is my data in txt
file:
Chair
Table
Planks
Door
Each separated by a new line.
So how do I convert it into a list
so that it's output would be like this:
['Chair', 'Table', 'Planks', 'Door']
Every time I try to convert it into a list
, it's new line character getting printed in the list
as well.
CodePudding user response:
You need to open
the file, then split
it's contents:
with open('test.txt', 'r') as f:
print(f.read().split())
['Chair', 'Table', 'Planks', 'Door']
CodePudding user response:
Try the python split method.
your_list.split("\n")
CodePudding user response:
a="""
Chair
Table
Planks
Door
"""
with newline character
print([i for i in a.split('\n')])
output - ['', 'Chair', 'Table', 'Planks', 'Door', '']
without newline character (avoid newline charecter)
print([i for i in a.split('\n') if i != ""])
output - ['Chair', 'Table', 'Planks', 'Door']
CodePudding user response:
opening the file in read mode
my_file = open("file1.txt", "r")
reading the file
data = my_file.read()
replacing end splitting the text when the newline ('\n') is seen.
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()
output :
['Chair', 'Table', 'Planks', 'Door']