I am writing this code to read a text file and then print the line number after each line here is my code
with open("newfile.txt") as f:
for line in f:
x=1
y=str(x)
print(line)
print(x)
x=x+1
f.close()
I should expect some thing like that
Line one
1
Line two
2
Line three
3
but instead I am getting
Line one
1
Line two
1
Line three
1
Why is that !?
You can just use enumerate() :
with open("newfile.txt") as f:
for num,line in enumerate(f,1):
print line,'\n',num
Also note that you don't need to close the file when you use the with statement. It will automatically does it for you.
And about the x variable in your code, you shouldn't initialized it in your loop, you need to put x=1 out of the loop.
Adding comments to your code will help you see why you always print out 1.
with open("newfile.txt") as f:
for line in f:
x=1 # x is now equal to 1
y=str(x) # x is still 1, y is now equal to '1'
print(line) # prints out the line
print(x) # 1 is printed
x=x+1 # you now add 1 to x, but don't do anything with this
# updated value, because in the next loop x is again
# initialised to 1
f.close()
The problem is that you are initializing x to 1 inside the loop and before the print statement.
try:
x = 1
with open("newfile.txt") as f:
for line in f:
y = str(x)
print(line)
print(x)
x += 1
The issue with the code would be the x=1 inside of the loop. By moving that outside and initializing that before you should get the result you want. For example:
x=1
with open("newfile.txt") as f:
for line in f:
y=str(x)
print(line)
print(x)
x=x+1
This should work
Related
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()
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.
Could anybody advice me if there is any way to keep file pointer in the nested IF clause.
I have to parse the file, and based on its content, different code blocks should process the file.
I came up with nested IF loops.
The code:
import re
with open('smartctl.txt', 'r') as file:
line = file.readlines()
for x in line:
matchIP = re.search('Checking', x)
if matchIP:
print(x)
Match_Micron55 = re.search('Micron_5100', x)
Match_Intel = re.search('INTEL', x)
Match_Micron600 = re.search('Micron_M600', x)
Any_Micron = re.search('Micron', x)
if Match_Micron55:
print("here we have Micron55")
elif Match_Intel:
print("here we have Intel")
elif Match_Micron600:
print('here we have Micron 600')
mline = line
print("file is open")
check = ""
for y in mline:
if y == x:
check == True
continue
if y.startswith(' 1 Raw_Read_Error_Rate') and check == True:
print(y)
continue
if y.startswith(' 5 Reallocated_Sector_Ct') and check == True:
print(y)
continue
if y.startswith('173 Unknown_Attribute') and check == True:
print(y)
break
elif Any_Micron:
print('Here we have unsorted values')
As you can see I read the file as line.
Then I go with variable X through the file.
Then, when I fall in IF condition, I have to CONTINUE reading the file: that's keep the file pointer and continue reading exactly from the place I went into the IF loop. I use 2 loops here with X and Y variables (for x in line and for y in mline). Could you tell me please if I can continue reading the same file in the second(nested) If confidition?
The method seems to be non working. Apart from creating Y variable I have also tried using X in the nested IF clause but was not succeed. The x (line) variable seems to not keep its value on the second IF entry.
I suspect your problem lies in the following code:
line = file.readlines()
for x in line:
The fileread is returning a line from the file, the x in line is iterating through the line a character at a time. I bvelieve you should restructure your code as follows:
replace:
with open('smartctl.txt', 'r') as file:
line = file.readlines()
for x in line:
with:
with open('smartctl.txt', 'r') as file:
for x in file.readlines():
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.
I would like to take a large file like this in Python 2.7:
123 456 GTHGGGTH
223 567 FGRTHSYS
12933 4656832 GJWSOOOSKKSSJ
.....
and I want to read in the file line by line, disregard the third element, and subtract the second element in each line by the first element. Thus line 1 above would return 333.
I have tried this so far:
def deleteLast(list):
NewL = list.pop()
return NewL
f = open(file_name, 'r')
line = f.readline()
while line:
L = line.split()
L2 = deleteLast(L)
L3 = [int(number) for number in L2]
Length = L3[1]-L3[0]
print Length
f.close()
But, when I try this the compiler says:
ValueError: invalid literal for int() with base 10: 'T'
All help is appreciated.
That is because list.pop() is returning the "popped off" item, it doesn't return the list again.
Instead of this deleteLast function you have written, it would be better just to use a slice like this:
L2 = line.split()[0:2]
You are going to run into another problem later because your while loop isn't advancing at all. Consider using a for loop instead.
You can try something like this :
In [8]: with open("abc") as f: #always use with statement when handling files
...: for line in f:
...: x,y=map(int,line.split()[:2])
...: print y-x
...:
333
344
4643899
try the following:
with open(file_name, 'r') as f:
for line in f.readlines():
rowData = line.split()
left, right = map(int, rowData[:2])
length = right - left
print length
Or:
from operator import sub
with open(file_name, 'r') as f:
for line in f.readlines():
print sub(*map(int, line.split()[:2])[::-1])
f = open(file_name, 'r')
for line in f.readlines():
x, y = line.split(' ')[:2]
print int(y) - int(x)