7 odpowiedzi
+ 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)
+ 8
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)
+ 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
+ 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)
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.
0
Python me kya kya hota hai mujhe to kuchh samjh me nahi aa raha hai
0
RAJ KUMAR SINGH Do you start python course brother? You can do anything whatever you want with python.