Jumping to a specific line python - python

I am using the following code to read a text file and create an array list out of the text found in the file.
But currently I am reading the whole file.
How can I read for example from line no. 16 onwards in this case?
array = []
with open(path, 'r') as f:
for line in f.readlines():
for action in all_actions:
if action in line:
array.append(action)

You can use
array = []
exit_line = 16
start_line = 10
with open(path, 'r') as f:
for index, line in enumerate(f.readlines()[start_line:]):
for action in all_actions:
if action in line:
array.append(action)
if index == exit_line - 1:
break
and then to make an if condition to exit/ break at line 16 that is the index +1 .

Try (explanation in code comments):
array = []
with open('path', 'r') as f:
# x here is a loop (lines) counter provided by the enumerate function
for x, line in enumerate(f.readlines()):
for action in all_actions:
if action in line:
array.append(action)
# if the counter reaches 16 BREAK out of the loop
if x == 16:
print ("Line 16 exiting loop")
break

Related

Python how to start reading file after a specific line to a specific line?

I need to make my python code reads emma.txt file after line 32 to line 16266.
fin = open("emma.txt", encoding="UTF-8")
fin.readline()
line= fin.readline()
word = line.strip()
print(word)
fin.close()
fin = open("emma.txt", encoding="UTF-8")
for line in fin:
word = line.strip()
print(word)
The problem is solved with the code below
emma = open("emma.txt", encoding="UTF-8")
lines = emma.readlines()[31:16265]
for line in lines:
print(line.rstrip())
Since storing all lines into memory is not a good idea. you can use islice from itertools module which gives you ability to pick which items you want from an iterator. click
from itertools import islice
with open('your_file.txt') as f:
for line in islice(f, 31, 16266):
# do what you wanna do
It is much more efficient and clean.
Try this:
with open("test.py", "r") as file:
lines = file.readlines()
lines = lines[31:16265]
print(lines)
This saves all the lines as a list and then makes the list the 31st index (32nd line) to the 16265th index (16266th line).
My mistake, my previous answer was incorrect. I have changed it to
lines = lines[21:12265]
Use this to get your answer fast and efficient
start = 31
end = 16266
with open("test.py", "r", encoding="UTF-8") as file:
lines = file.readlines()[start:end]
print(lines)
def read_range_lines(filename, start, end):
if end > start:
return
with open(filename, "r") as file:
count = 0
while count < start - 1:
file.readline()
count += 1
while count < end:
print(file.readline())
count += 1
Using enumerate to track line numbers.
with open('f3.txt') as f:
for line_no, line in enumerate(f):
if 31 <= line_no <= 16265: # assuming line numbered from 0
# Processing of desired lines
print(line)
elif line_no > 1626i5:
# Not required but avoids futher unnecessary file reading
break

How to choose what line to print from a txt file in python

I want to print a specific line from a txt file like from a txt file like this:
"line number 1"
"line number 2"
"line number 3"
I want to print line number 3 and 2 how do I do that?
This code will help you:
from collections import deque
try:
num = int(input("Number of last lines to print:"))
except:
num = 1
a_file = open("data.txt")
lines = a_file.readlines()
for line in deque(lines, num):
print(line)
Let's say you want to print from start_line to end_line. You can do as follows:
with open("test.txt", "r") as f:
rows = f.readlines()[start_line - 1 : end_line]
print(rows)
If start_line is 2 and end_line is 3, it will print 2nd and 3rd lines of test.txt
To avoid loading the whole file in memory do not use readlines:
fname = "data.txt"
skip_num = 2
with open(fname) as f:
for _ in range(skip_num):
f.readline()
for line in f:
print(line)
Cheers!

python: index out of range in txt file

I'm writing a script to automatically annotate a txt file.
I open the txt file and segment it into a list of lines. Then I iterate over every line. I want the PC to check if the previous element in the list (the line before in the text) is an empty element (the paragraph division in the text) and if it so to put an annotation.
final_list = []
something = open(x, 'r', encoding='utf8', errors='ignore')
file = something.read()
y = file.split("\n")
for position, i in enumerate(y):
if position == 0:
final_list.append(i)
elif position > 0:
z = i[position-1]
if z == '':
final_list.append("<p>"+i)
return final_list
I expect to a have a final list with all the element of the previous line with some of them marked with the element, but when I iterate over the list Python gives me a
IndexError: string index out of range
I cannot understand where is the problem.
As you are not using values of list, instead of enumerate take length of list and iterate.
You can try this,
for position in range(len(y)):
if position == 0:
final_list.append(i)
elif position > 0:
z = y[position-1]
if z == '':
final_list.append("<p>"+i)
How about something like this :
last_line = ''
output_lines = []
with open('file.txt', 'r') as f:
for line in f:
line = line.strip()
if last_line == '': # if last line was empty, start a new paragraph
output_lines.append('<p>')
output_lines.append(line)
elif line == '': # if current line is empty close the paragraph
output_lines.append('</p>')
else:
output_lines.append(line)
last_line = line

Python: How do I calculate the sum of numbers from a file?

How do I calculate the sum of numbers from a .txt file?
Data in file is formatted as:
7
8
14
18
16
8
23
...
I read the data from the file and assign every line value to 'line' vatiable, but I want to get something like: result = 7+8+14+...
f = open('data.txt', 'r') #LOOP AND READ DATA FROM THE FILE
for line in f:
code
This is most compact code I can think of right now:
(updated to handle the n at the end, thanks, #JonClements!)
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin if line.strip().isnumeric())
For the code structure you have, you can also go for this:
f = open('data.txt', 'r')
ans = 0
for line in f:
try:
ans += int(line.strip())
except ValueError:
pass
Edit:
Since the confusion with the 'n' has been cleared, the first example can be as simple as
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin)
Or even this one-liner:
ans = sum(int(line) for line in open('file.txt', 'r'))
But there are certain risks with file handling, so not strongly recommended.
Keep it simple:
with open('data.txt', 'r') as f:
result = sum(map(int, f))
int is mapped over each line from f, then sum() adds up the resulting integers.
file = open("data.txt", "r")
numbers = []
for line in file:
numbers.append(int(line))
print(sum(numbers))
This basically just creates a list of numbers, where each line is a new entry in the list. Then it shows the sum of the list.
A simple solution is, it will take care of the \n at the end of each line as well, based on steven's and AChamp's suggestion
with open("abc.txt","r")as f:
print(sum(int(x) for x in f))
Here is a solution (consider all of the lines are numbers):
def calculate_number_in_file(file_path):
with open(file_path, 'r') as f:
return sum([int(number.strip()) for number in f.readlines()])
with open ('data.txt', 'r') as f:
data = f.readlines()
sum = 0
for line in data:
sum += int(line.strip())
print(sum)
On smartphone...
with open(filepath) as f:
lines = f.readlines()
numbers = [int(line) for line in lines]
print(sum(numbers))

How to write every other line in a text file?

inputFile = open('original_text.txt','r')
outputFile = open('half_text.txt','w')
line = inputFile.readline()
count = 0
for line in inputFile:
outputFile.write(line)
count += 1
if count % 2 == 0:
print(line)
inputFile.close()
outputFile.close()
It keeps skipping the 1st line. For instance, the text file right now has 10 lines. So it prints the 3rd 5th 7th and 9th. So I'm just missing the first.
This skips the first line because you read it and throw it away before the loop. Delete line 4,
line = inputFile.readline()
Add change the count parity to odd with
if count % 2 == 1:
For a slightly better design, use a boolean that toggles:
count = False
for line in inputFile:
outputFile.write(line)
count = not count
if count:
print(line)
inputFile.close()
outputFile.close()
I tried running the program on itself:
inputFile = open('this_file.py', 'r')
count = False
outputFile.write(line)
if count:
outputFile.close()
use next to skip the next line. You may need to watch for a StopIteration error on the call to next(fh) if you have odd lines.
outputFile = open('half_text.txt','w')
with open('original_text.txt') as fh:
for line1 in fh:
outputFile.write(line1)
try:
next(fh)
except StopIteration:
pass
outputFile.close()
The for loop will go over the file line by line and when you use the readline, it will advance the pointer forward inside the loop. Therefore odd will go over odd numbered lines and even goes over even numbered lines.
with open (path, 'r') as fi:
for odd in fi:
even = fi.readline()
print ('this line is odd! :' + odd)
print ('this line is even! :' + even)

Categories

Resources