Go to a specific line in Python?
Use Python Standard Library's linecache module:
line = linecache.getline(thefilename, 33)
should do exactly what you want. You don't even need to open the file -- linecache
does it all for you!
How to jump back to a specific line of code (Python)
albeit loop best suited your case, but you really could jump back to a specific line:
import sys
def jump(lineno):
frame = sys._getframe().f_back
called_from = frame
def hook(frame, event, arg):
if event == 'line' and frame == called_from:
try:
frame.f_lineno = lineno
except ValueError as e:
print "jump failed:", e
while frame:
frame.f_trace = None
frame = frame.f_back
return None
return hook
while frame:
frame.f_trace = hook
frame = frame.f_back
sys.settrace(hook)
use this function to jump back to line key = keyRead()
.
besides, there are goto implementation in the wild.
How to jump to a particular line in a huge text file?
linecache:
The
linecache
module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by thetraceback
module to retrieve source lines for inclusion in the formatted traceback...
Go to a specific line in file
Do it with iterators and generators, files xreadlines
(python 2) it is lazily evaluated so the file is not been loaded into memory until you consume it:
def drop_and_get(skiping, it):
for _ in xrange(skiping):
next(it)
return next(it)
f = xrange(10000)#lets say your file is this generator
drop_and_get(500, iter(f))
500
So you can actualy do something like:
with open(yourfile, "r") as f:
your_line = drop_and_get(5000, f.xreadlines())
print your_line
You can actually even skip xreadlines
since the file object is an iterator itself
with open(yourfile, "r") as f:
your_line = drop_and_get(5000, f)
print your_line
Go to a specific line in terminal using Python
You will have to use a package like curses
to take control of the terminal. That's what apps like vi
use to do their drawing. That lets you draw strings at specific row and column position.
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']]
Editing specific line in text file in Python
You want to do something like this:
# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
# read a list of lines into data
data = file.readlines()
print data
print "Your name: " + data[0]
# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'
# and write everything back
with open('stats.txt', 'w') as file:
file.writelines( data )
The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.
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 to go back to a specific line
You're looking for a goto
statement. Back in 1968, Dijkstra wrote a famous paper called Go To Statement Considered Harmful that explained why you should not be looking for goto
.
The right thing to do is structure your code.
The simplest change is this:
print "1) Add"
print "2) Substract"
print "3) Multiply"
print "4) Divide"
print "5) Exit"
while True:
x=input("Choose an operation: ")
# ...
However, you can do better. Take isolated pieces of code and separate them into functions that you can call. If two (or, in your case, four) pieces of code are nearly identical, abstract them into a single function that takes a parameter, instead of repeating the same code four times. And so on.
But really, even without any functions, you can get rid of most of the repetition:
import operator
print "1) Add"
print "2) Substract"
print "3) Multiply"
print "4) Divide"
print "5) Exit"
while True:
x=input("Choose an operation: ")
if x==5:
break
y=input("How many numbers do you need to operate: ")
operands=[input('Value {}'.format(i+1)) for i in range(count)]
if x==1:
op, value = operator.add, 0
elif x==2:
op, value = operator.sub, 0
elif x==3:
op, value = operator.mul, 1
elif x==4:
op, value = operator.truediv, 1
for operand in operands:
value = op(value, operand)
print value
The only reason I had to import operator
above was to get those add
, sub
, etc. functions. These are trivial, so you could write them yourself:
def add(x, y):
return x+y
# etc.
Then, instead of this:
op, value = operator.add, 0
… do this:
op, value = add, 0
… and the same for the other three.
Or you can define them in-place with lambda
:
op, value = (lambda x, y: x+y), 0
Still, you shouldn't do either of these. As simple as defining add
, sub
, mul
, and truediv
is, it's even simpler to not define them. Python comes with "batteries included" for a reason, and if you're avoiding using them, you're making your life (and the lives of anyone who has to read, maintain, etc. your code) harder for absolutely no reason.
Related Topics
What Is Sys.Maxint in Python 3
Python: Random Selection Per Group
Get All Object Attributes in Python
Find Usa Phone Numbers in Python Script
Pandas: Convert Dtype 'Object' to Int
Pandas Unique Values Multiple Columns
Printing Without Newline (Print 'A',) Prints a Space, How to Remove
How to Normalize a Url in Python
Split an Integer into Digits to Compute an Isbn Checksum
How to "Zip Sort" Parallel Numpy Arrays
How to Call Python Code from C Code
Preprocessing in Scikit Learn - Single Sample - Depreciation Warning
Type Hints with User Defined Classes
Duplicate Items in Legend in Matplotlib
How to Upload a File to Google Cloud Storage on Python 3
Python: Why Does My List Change When I'm Not Actually Changing It