How to read specific lines from a file (by line number)?
If the file to read is big, and you don't want to read the whole file in memory at once:
fp = open("file")
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
fp.close()
Note that i == n-1
for the n
th line.
In Python 2.6 or later:
with open("file") as fp:
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
Read a specific line or character from a text file, not recognizing the text
Your code works, but it cannot recognize the characters because readlines() also includes a newline character, so it reads 'x\n' rather than 'x'. Therefore there is no literal match. Replace .readlines()
with .read().splitlines()
to solve this.
How do I read a specific line on a text file?
as what Barmar said use the file.readlines(). file.readlines makes a list of lines so use an index for the line you want to read. keep in mind that the first line is 0 not 1 so to store the third line of a text document in a variable would be line = file.readlines()[2]
.
edit: also if what copperfield said is your situation you can do:
def read_line_from_file(file_name, line_number):
with open(file_name, 'r') as fil:
for line_no, line in enumerate(fil):
if line_no == line_number:
file.close()
return line
else:
file.close()
raise ValueError('line %s does not exist in file %s' % (line_number, file_name))
line = read_line_from_file('file.txt', 2)
print(line)
if os.path.isfile('file.txt'):
os.remove('file.txt')
it's a more readable function so you can disassemble it to your liking
How do you read a specific line of a text file in Python?
What are the conditions of this line? Is it at a certain index? Does it contain a certain string? Does it match a regex?
This code will match a single line from the file based on a string:
load_profile = open('users/file.txt', "r")
read_it = load_profile.read()
myLine = ""
for line in read_it.splitlines():
if line == "This is the line I am looking for":
myLine = line
break
print myLine
And this will give you the first line of the file (there are several other ways to do this as well):
load_profile = open('users/file.txt', "r")
read_it = load_profile.read().splitlines()[0]
print read_it
Or:
load_profile = open('users/file.txt', "r")
read_it = load_profile.readline()
print read_it
Check out Python File Objects Docs
file.readline([size])
Read one entire line from the file. A trailing
newline character is kept in the string (but may be absent when a file
ends with an incomplete line). [6] If the size argument is present and
non-negative, it is a maximum byte count (including the trailing
newline) and an incomplete line may be returned. When size is not 0,
an empty string is returned only when EOF is encountered immediately.Note Unlike stdio‘s fgets(), the returned string contains null
characters ('\0') if they occurred in the input.file.readlines([sizehint])
Read until EOF using readline() and return
a list containing the lines thus read. If the optional sizehint
argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to
an internal buffer size) are read. Objects implementing a file-like
interface may choose to ignore sizehint if it cannot be implemented,
or cannot be implemented efficiently.
Edit:
Answer to your comment Noah:
load_profile = open('users/file.txt', "r")
read_it = load_profile.read()
myLines = []
for line in read_it.splitlines():
# if line.startswith("Start of line..."):
# if line.endswith("...line End."):
# if line.find("SUBSTRING") > -1:
if line == "This is the line I am looking for":
myLines.append(line)
print myLines
Only read specific line numbers from a large file in Python?
Here are some options:
- Go over the file at least once and keep track of the file offsets of the lines you are interested in. This is a good approach if you might be seeking these lines multiple times and the file wont be changed.
- Consider changing the data format. For example csv instead of json (see comments).
- If you have no other alternative, use the traditional:
def get_lines(..., linenums: list):
with open(...) as f:
for lno, ln in enumerate(f):
if lno in linenums:
yield ln
On a 4GB file this took ~6s for linenums = [n // 4, n // 2, n - 1]
where n = lines_in_file
.
Python function that will read a specific line in a .txt file
Wrong indexing -->
sample file im using:
1
2
3
4
5
def txtfile_line(file_path: str,line_number: int):
open_file = open(file_path)
read_file = open_file.readlines()
if line_number > len(read_file):
return ("invalid index")
if read_file[line_number-1] == '\n':
return ("Empty Line")
else:
return read_file[line_number - 1]
print(txtfile_line("file.txt",5))
5
when running print(txtfile_line("file.txt",6))
this modified function will give
invalid index
remember that list indexes start at 0, so a list with a length of 5 would actually be indexed 0-4!
How to read a specific line from a text file in python
You're reading your line with the newline character at the end. Your line1
variable probably contains string '1\n'
.
Try calling .strip()
immediatelly after readline:
line1 = file.readline().strip()
line2 = file.readline().strip()
line3 = file.readline().strip()
How to read a specific line in a file?
Just before if line == "List: \n" + "\n"
you could print(repr(line))
and see that it is not the value you are looking for. lines
is a list of lines and will have at most a single newline character and its at the end of the line. The final line may not have a newline depending whether the file terminates with one.
Instead, just look for the contents of a single line. Stripping the line deals with the newline and any inconvenient whitespace on the end and makes up for small mistakes in the file.
with open("file.txt", "r") as f:
lines = f.readlines()
if not lines or lines[0].strip() != "List:":
print("Invalid file")
elif len(lines) < 2 or not(lines[1].strip()):
print("\nThere are no lists!")
You don't need to read the entire file to do this. zip
combines two collections, stopping at the shortest. leveraging that you could
with open("file.txt", "r") as f:
lines = [line.strip() for _, line in zip(range(2), f)]
if not lines or lines[0] != "List:":
print("Invalid file")
elif len(lines) < 2 or not(lines[1].strip()):
print("\nThere are no lists!")
How to move the cursor to a specific line in python
Does this work? If you don't want to read the entire file with .readlines()
, you can skip a single line by calling .readline()
. This way you can call readline()
as many times as you want to move your cursor down, then return the next line. Also, I don't recommend using line != '<end>\n'
unless you're absolutely sure that there will be a newline after <end>
. Instead, do something like not '<end>' in line
:
def create_list(pos):
list_created = []
with open('text_file.txt', 'r') as f:
for i in range(pos):
f.readline()
line = f.readline() #And here I read the first line
while not '<end>' in line:
line = line.rstrip('\n')
list_created.append(line.split(' '))
line = f.readline()
f.close()
return list_created
print(create_list(2)) #Here i need to create a list starting from the 3rd line of my file
text_file.txt:
Something
<start>
MY FIRST LINE
MY SECOND LINE
<end>
Output:
[['MY', 'FIRST', 'LINE'], ['MY', 'SECOND', 'LINE']]
Related Topics
How to Continue a Loop After Catching Exception in Try ... Except
Converting Pandas Column of Comma-Separated Strings into Integers
List Available Font Families in 'Tkinter'
How to Divide Each Column of Pandas Dataframe by a Series
Get the Row(S) Which Have the Max Value in Groups Using Groupby
Parentheses and Quotation Marks in Output
Using Python, How to Access a Shared Folder on Windows Network
How to Remove Nan from List Python/Numpy
How to Count the Total Number of Words in a Pandas Dataframe Cell and Add Those to a New Column
How to Make a Tkinter Label Background Transparent
Python Pandas Valueerror Arrays Must Be All Same Length
Saving the Output of a Python Program
Discord Bot Messaging a User With a Specific User Id
How to Downgrade Python from 3.7 to 3.5 in Anaconda
How to Remove Square Brackets from List in Python
Python - Use Previous Row'S Value to Update the New Rows Values