Read data as list in python?

python read text file into list of strings
how to put a text file into a list python
python read list from text file
python read list from file
python write list to file
python list
python read words from file into list
python read file
     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female

This is the data that i have in my book.csv file.

>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]

After following commands, l1 stores this value:

['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

The following output is string in list format, but i want nested list like this:

[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

What changes do I need to make?


You could do the following, using ast.literal_eval:

import pandas as pd
import ast

data = [['[133,28,23]', 'female'],
        ['[157,22,87]', 'male'],
        ['[160,33,77]', 'male'],
        ['[122,87,20]', 'female'],
        ['[120,22,20]', 'female']]

df = pd.DataFrame(data=data, columns=['x', 'y'])
df['x'] = df['x'].apply(ast.literal_eval)
result = df['x'].tolist()

print(result)

Output

[[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]

Reading and Writing Lists to a File in Python, Storing these data structures persistently requires either a file or a database to work with. This article describes how to write a list to file, and how to read that list​  To write data in a file, and to read data from a file, the Python programming language offers the standard methods write() and read() for dealing with a single line, as well as writelines() and readlines() for dealing with multiple lines.


You can use json:

>> import json
>> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>> l1=[json.loads(h) for h in fd.x]
[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

Or ast

>> import ast
>> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>> l1=[ast.literal_eval(h) for h in fd.x]
>> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

Python - How to read a file into a list?, Python example to read a log file, line by line into a list. # With '\n', ['1\n', '2\n', '3'] with open('/www/logs/server.log') as f: content = f.readlines()  Python – How to read a file into a list? Python example to read a log file, line by line into a list. 1. Read File -> List. 1.1 A dummy log file. 1.2 is included.


One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):

from io import StringIO

inp = """     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female"""

# Read data
df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
# Remove brackets, split and convert to int
df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
# Print
l1 = [h for h in df.x]
print(l1)

Output:

[[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]

Python - Most elegant way to read lines of file into list, In this case, every element in the list contain a \n in the end the string, which would be extremely annoying in some cases. And there will be  In this article we will discuss different ways to read a file line by line in Python. Suppose we have a file data.txt in same directory as our python script. Let’s see how to read it’s contents line by line. Solution for Small Files : Get list of all lines in file using readlines() First basic and inefficient solution is using function


Python - Lists, f = open('my_file.txt', 'r+') my_file_data = f.read() f.close()The above code opens '​my_file.txt' in read mode then stores the data it r The list defined above has items that are all of the same type (int), but all the items of a list do not need to be of the same type as you can see below. # Define a list heterogenousElements = [3, True, 'Michael', 2.0] The list contains an int, a bool, a string, and a float. Access Values in a List. Each item in a list has an assigned index value.


How to read text file into a list or array with Python?, One of the most common tasks computer programs perform is reading information from and writing information to files. Luckily, Python provides a number of useful  The + tells the python interpreter to open file with read and write permissions. To append data to an existing file use the command open ("Filename", " a ") Use the read function to read the ENTIRE contents of a file. Use the readlines function to read the content of the file one by one. Prev.


Loading a file into a list, Reading a text file is a vital part in programming. Mostly when a file is read, its contents are stored in a data structure such as an array, list, map  There are actually a number of ways to read a text file in Python, not just one. If you need to extract a string that contains all characters in the file, you can use the following method: file.read() The full code to work with this method will look something like this: file = open(“testfile.text”, “r”) print file.read()