Python: Understanding indexing in the use of enumerate with readline - python

Python code:
myfile = open("test-file.csv", "r")
for k, line in enumerate(myfile,0):
if k == 0:
myline = myfile.readline()
print(myline)
break
myfile.close()
and test-file.csv is:
0. Zeroth
1. First
2. Second
3. Third
The output is
1. First
Why don't I get
0. Zeroth
?

By the time you call myfile.readline() you have already consumed the zeroth line. (It is stored in the variable line, and the variable k holds its index 0, which is the condition you are checking).
Then, you read another line (the "first" line) from myfile. Try printing line instead of myline.

Because "zeroth" has already been read in the loop,
myfile = open("test-file.csv", "r")
for k, line in enumerate(myfile,0):
if k == 0:
print(line) # this should output "zeroth"
myline = myfile.readline() #this will read "First"
print(myline)
break
myfile.close()

Related

Why is my code not showing any output? I am trying to use while loop to debug the error i was getting before it

f = file.readlines()
l = 0
while l <= len(f):
for i in range(l):
x = f[i]
l += 1
for a in x:
if a == "a":
f.pop(i)
break
else:
continue
print(f)
file.close()
I want to pop any line from the data which has any character 'a' in it.
You don't need to manage your own line counter and iterate over each line
character by character. The file itself is iterable without using readlines, and the in operator tells you at once if "a" is a character in a given line.
with open("filename") as f:
for line in f:
if "a" in line:
print(line, end="") # line already ends with a newline
Im not quite understanding the way your code is supposed to work, but this would solve your problem too:
f = file.readlines()
for line in reversed(f):
if "a" in line:
f.remove(line)
for i in range(l) when l is zero will cause the loop to run zero times.

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

Use content of .txt file line as input for python3 variable

I have a python script which print in a text file every prime.
I would like my script to pickup the list where it left off so basically take the contents of the last line as a variable.
Here is my current script:
def calc():
while True:
x = 245747
y = (100**100)**100
for n in range (x,y):
if all(n%i!=0 for i in range (2,n)):
a=[]
a.append(n)
fo = open('primes.txt', 'a+')
print(n)
print ("", file = fo)
print ((a), file = fo)
fo.close
s = input('To do another calculation input yes, to quit input anything else...')
if s == 'yes':
continue
else:
break
calc()
I would like the variable x to get as an input the last line of primes.txt
There should be on that last line "[245747]" if the greatest prime number is 245747.
How could I achieve that? Thanks!
You can do use readlines and get the last item of the list:
file = open("primes.txt", "r").readlines()
x = file[len(file)-1]
I think this should work.
You can just get rid of the 2 "[" and "]" with split or something similar.

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 check if the next element in a text file is 1 more than the previous element?

I have a programming homework question:
What is a good method to create a script that checks if the next element in a text file is equal to the previous plus 1 and report back the line in the text file that fails to meet this condition?
The text file looks like:
1
3
2
4
What I have so far:
filename=input('filename')
easy_text_file = open(filename, "rU")
store=1
count=0
for entry in easy_text_file:
entry_without_newline = entry[:-1]
data_list=list(entry_without_newline)
if store != data_list[0]:
print(store)
print(data_list[0])
count=count+1
print('This line does not satisfy the condition at line: ',count)
break
store=data_list[0]
print(store)
count=count+1
If I edit the text file to be:
1
2
3
4
6
5
It still returns "This line does not satisfy the condition at line: 1"
It seems that, you just have to keep track on two consecutive lines and check the condition for pair of lines -> 1-2 2-3 3-4 4-5 ...
This code works fine, I am just reading a line and keeping the track of previous line.
x=True
count=0
f=open("text.txt")
for line in f:
if (x==True): #This condition will be true just once.(for first line only)
prevline=line
line = f.next() #reading the second line. I will save this line as previous line.
x=False
a=int(prevline) #typecasting
b=int(line)
a=a+1
if(a!=b):
print "this line does not satisfy the condition at line:",count
prevline=line #keeping the track of previous line
count=count+1
f.close()
Read the first line of the file before entering the loop. This will allow you to initialise the expected sequence without assuming that the first number in the file is 1.
Once initialised, just keep track of the value that you expect on the next line, read a line from the file, convert it to an integer, compare it to the expected value, and print an error message if the values do not agree.
You don't need to convert each line to a list, just use int() - which also ignores new line characters. You should also handle non-numeric data - int() will raise ValueError if it can't convert the line to a valid integer.
Also, you can keep track of line numbers using a counter (as per your code), or by using enumerate().
Putting all of that together you might code it like this:
filename = input('filename')
with open(filename, 'rU') as easy_text_file:
expected = int(next(easy_text_file)) + 1 # initialise next line from first line
for line_number, entry in enumerate(easy_text_file, 2):
try:
entry = int(entry)
if entry != expected:
print("Line number {} does not satisfy the condition: expected {}, got {!r}".format(line_number, expected, entry))
expected = entry + 1
except ValueError:
print("Line number {} does not contain a valid integer: {!r}".format(line_number, entry)
Build a generator to return each line as an int
Read the first line, and build a counter that yields the expected values
Compare each value and expected value
Where they differ, print the line number, the value and expected value and break
Where a break didn't occur (the else associated with the for) - print all good
Eg:
from itertools import count
with open('testing.txt') as fin:
lineno = 0
lines = map(int, fin)
try:
expected = count(next(lines) + 1)
for lineno, (fst, snd) in enumerate(zip(lines, expected), 2):
if fst != snd:
print('problem on line {}: got {}, expected {}'.format(lineno, fst, snd))
break
else:
print('All was fine')
except StopIteration:
print('File was empty')
except ValueError as e:
print('Error converting line {} - {}'.format(lineno + 1, e))
Another alternative :
easy_text_file = open("number.txt", "rU")
#directly iterate each line of easy_text_file, convert it to int and create list
initial = [int(line) for line in easy_text_file]
#Based your requirement : next value should be equal to previous + 1
#So we create list with starting point from first value to length of initial list
compare = range(initial[0], len(initial)+1)
#Using zip function to create a match tuple between those list
#Output of zip(initial, compare) => [(1,1),(2,2),(3,3),(5,4), ....]
#Then we compare between each values
for i, j in zip(initial, compare):
if i!=j:
print 'This line does not satisfy the condition at line: ', j
break
easy_text_file.close()
result :
>>>
This line does not satisfy the condition at line: 4
>>> initial
[1, 2, 3, 5, 5, 3, 5]
>>> compare
[1, 2, 3, 4, 5, 6, 7]
>>>

Categories

Resources