Python data file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python data file

How in Python can we read data from a text file and store them in a list or variable?

10th Apr 2024, 5:48 PM
ALKANE
ALKANE - avatar
7 Answers
+ 8
# Open the text file in read mode with open('data.txt', 'r') as file: # Read all lines from the file and store them in a list lines = file.readlines() # Now 'lines' contains each line of the text file as an element in the list print(lines)
10th Apr 2024, 6:49 PM
Oma Falk
Oma Falk - avatar
+ 7
Oma Falk , using: lines = file.readlines() has this issues: > the resulting list contains not only the strings from the file, but also a trailing new-line sequence: *\n* for each line from the file. these should be removed. > removing the new-line sequences could be done like: with open('test_1.txt', 'r') as file: lines = [item.rstrip() for item in file] print(lines)
10th Apr 2024, 7:52 PM
Lothar
Lothar - avatar
+ 4
It depends on the file format. For example you can CSV files using built in standard library. https://docs.python.org/3/library/csv.html There is also similar utility in pandas library to import CSV files to a dataframe. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html And there are external libraries to process Excel files too. If the data is in some custom text format, just get the data with the open() command and parse it using split(). https://docs.python.org/3/library/functions.html#open
10th Apr 2024, 6:49 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Lothar It preserves blank lines. If we don't want blank ("") in the list, we can: with open("text.txt") as fh: #file handler lines = fh.read().split() print(lines)
11th Apr 2024, 3:47 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
Here is an example code snippet to read data from a text file and store it in a list: # Open the file in read mode with open('data.txt', 'r') as file: # Read the contents of the file and store each line in a list data = file.readlines() # Print the data to verify print(data) You can use this code: - Replace 'data.txt' with the path to your text file. - The "with" statement ensures that the file is properly closed after reading its contents. - The "readlines()" method reads all lines from the file and returns a list where each element corresponds to a line in the file. By the way u can then use the "data" list to access the lines of the text file as elements of the list.
11th Apr 2024, 4:16 AM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar
0
Python me kya kya hota hai mujhe to kuchh samjh me nahi aa raha hai
12th Apr 2024, 2:13 PM
RAJ KUMAR SINGH
RAJ KUMAR SINGH - avatar
0
RAJ KUMAR SINGH Do you start python course brother? You can do anything whatever you want with python.
12th Apr 2024, 2:19 PM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar