How to read a text file into a list in Python
How to read a text file into a list in Python
The
contents of a file are a sequence of characters. The characters are
interpreted as a list of values by splitting on a delimiter. For
example, a comma-separated values (CSV) file with the content "1,2,3"
split on the delimiter ","
creates the list ["1", "2", "3"]
.
Use str.split()
to split a text file into a list
Call file.read()
to return the entire content of file
as a string. Call str.split(sep)
with this string as str
to return a list of the values of the file split by sep
.
```
my_file = open("sample.txt", "r")
content = my_file.read()
print(content)
```
Output
1,2,3
```
content_list = content.split(",")
my_file.close()
print(content_list)
```
Output
['1', '2', '3']
Use file.readlines()
to read a text file into a list
Call file.readlines()
to return a list where each item is a line from file
.
```
my_file = open("sample.txt", "r")
content_list = my_file.readlines()
print(content_list)
```
Output
['1\n', '2\n', '3\n']
Warning: If the entire content of the file is all on one line,
file.readlines()
will return a list containing one item instead of a list of individual items.
When our input lists are contain \n, we need to remove it and converting as a list. so, we can use below code
content_list =
[1\n2\n3\n] #input
```
content_list = content.split("\n")
# we are splitting a value and converting as a list in a required format
my_file.close()
print(content_list)
```
Output
['1', '2', '3']
How to save getting list values in a text file
```
#values = ['1', '2', '3']
content_list # Previously getting output list, we are using here
with open("filename.txt", "w") as output:
output.write(str(content_list))
```
Also, we can go with alternative method using json
```
```
import json
a = [1,2,3]
with open('test.txt', 'w') as f:
f.write(json.dumps(a))
#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
a = json.loads(f.read())
```
References - Building the future with software
link - https://www.adamsmith.haus/python/
link - https://www.adamsmith.haus/python/
Comments
Post a Comment