Why can't I print all lines that are two characters long? - python

This only prints the last line that's 2 in length. How can I make it print all of the previous lines 2 in length? This is where I am so far:
file_name = "file1.txt"
with open(file_name, "r") as f:
for line in f:
if len(line) == 2:
print line

You need to use strip() to strip the white space from the beginning and the end of each line to get correct line length. Otherwise your code should work fine.
file_name = "file1.txt"
with open(file_name, "r") as f:
for line in f:
if len(line.strip()) == 2:
print line
The line to be modified is line 5:
if len(line.strip()) == 2:

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!

Jumping to a specific line 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

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)

How to take an inputted file and count the letters in each word and print it

I have a text document of 7000 words that I have to go through and count the letters in each word. So I am stuck on trying to break up each line at the '/n' and having it count it. If someone could point me in the right direction, it would be very much appreciated.
from string import *
def main():
fname = raw_input("Enter filename: ")
infile = open(fname,'r')
lines = 0
for line in infile.readlines():
lines = lines + 1
letters = line.split(line)
x = str(letters)
print len(x)
print line
print lines
main()
You don't need to break up the file into lines using a linefeed, Python will do that for you. In your comment you said the file had one word per line, so you could do this:
line_count = 0
with open("test.txt") as f:
for line in f:
line_count += 1
print len(line)
print line
print line_count

Categories

Resources