while true loop in python can't be stopped [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with this loop in python:
i = 1
while True:
with open('/tmp/file.txt', 'r+') as f:
for line in f:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
result = Function()
if "statement" in result:
out = open('/tmp/result.txt', 'a+')
out.write(result)
out.close()
i = i + 10
else:
return i
I want first read file.txt line by line and then for each line count i till statement exists in result but this loop is infinitive... So I removed break and used return i instead. but no result
How can I tell the while True loop to be stopped when all lines from file.txt is read and for each line counter is completed?
UPDATE
what I want to process:
word1line1word2line1counter=1test
word1line1word2line1counter=2test
word1line1word2line1counter=3test
.
.
.
#`till my if condition is true` then
word1line2word2line2counter=1test
word1line2word2line2counter=2test
word1line2word2line2counter=3test
.
.
.
and so on
Thanks

I think you need to switch your loops around:
i = 1
with open('/tmp/file.txt', 'r+') as f:
for line in f:
result = ...
while "statement" in result:
with open('/tmp/result.txt', 'a+') as out:
out.write(result)
i += 10
result = ...
Although it is not at all clear what this algorithm is supposed to be doing

I found the answer:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
for line in f:
i = 1
line=line.strip('\r\n ')
while True:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
print work
result = Function()
if "statement" in result:
out.write(result)
i += 10
else:
break
out.close()

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

Why does my program ask for input that comes second?

So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
When I run the program it works fine. However, It asks the user to input the text first and the line number second.
What is the reason for this and how can I fix it?
If you want to fix the problem, just split the one line into two:
Instead of:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
Do:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
And as the answer #Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.
Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?
Here's a more robust approach:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + '\n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')

Modify specific index of any line in a text file [duplicate]

This question already has answers here:
Change specific value in CSV file via Python
(4 answers)
Closed 2 years ago.
I have this txt file with usernames and some data related to them
vac3,Javier Jerez,34,Femenino,0,0
jotaaa23,Ssef Sef,34,Masculino,0,0
asd,Asdas Asd,23,Masculino,0,0
attd,Asd Asd,23,Femenino,0,0
ssdfd,Dgs Sef ,24,Femenino,0,0
asdfsdfd,Javier Jerez,12,Masculino,0,0
I want to modify the last 2 numbers
For example vac3 won a game with 90 points in 7 shots, i want the new list to be
vac3,Javier Jerez,34,Femenino,90,7
jotaaa23,Ssef Sef,34,Masculino,0,0
asd,Asdas Asd,23,Masculino,0,0
attd,Asd Asd,23,Femenino,0,0
ssdfd,Dgs Sef ,24,Femenino,0,0
asdfsdfd,Javier Jerez,12,Masculino,0,0
I've tried everything and nothing seems to work, i know i have to read the txt to a list, then rewrite data in that list, and then overwrite the whole txt. May i get some help pls.
Try this:
with open('players.txt', 'r') as f:
players = []
data = f.readlines()
winner = 'vac3'
scores = ['90', '7']
for line in data:
player = line.split(',')
if player[0] == winner:
player[4] = scores[0]
player[5] = scores[1]
players.append(player)
with open('players.txt', 'w') as f:
f.writelines('')
for player in players:
plr = ','.join(player) + "\n"
f.write(plr)
If you don't want to use csv.reader:
who, score, shots = "vac3", 90, 7
with open("yourfile.txt", "r") as f:
with open('newfile.txt', 'w') as out:
for line in f:
fields = line.rstrip().split(',')
if fields[0] == who:
fields[4] = score
fields[5] = shots
out.write(','.join(fields) + '\n')
You can use regex to identify the pattern and replace
import re
inpt = "vac3,90,7".split(',')
fmt = f"^({inpt[0]},.*,)\d+,\d+$"
new_txt = ""
with open('t.txt', 'r') as read_f, open('new.txt', 'w') as write_f:
for line in read_f:
new_txt += re.sub(fmt, fr"\g<1>{inpt[1]},{inpt[2]}", line)
write_f.write(new_txt)

When I open a text file, it only reads the last line

Say customPassFile.txt has two lines in it. First line is "123testing" and the second line is "testing321". If passwordCracking = "123testing", then the output would be that "123testing" was not found in the file (or something similar). If passwordCracking = "testing321", then the output would be that "testing321" was found in the file. I think that the for loop I have is only reading the last line of the text file. Any solutions to fix this?
import time
import linecache
def solution_one(passwordCracking):
print("Running Solution #1 # " + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
startingTimeSeconds = time.time()
currentLine = 1
attempt = 1
passwordFound = False
wordListFile = open("customPassFile.txt", encoding="utf8")
num_lines = sum(1 for line in open('customPassFile.txt'))
while(passwordFound == False):
for i, line in enumerate(wordListFile):
if(i == currentLine):
line = line
passwordChecking = line
if(passwordChecking == passwordCracking):
passwordFound = True
endingTimeSeconds = time.time()
overallTimeSeconds = endingTimeSeconds - startingTimeSeconds
print("~~~~~~~~~~~~~~~~~")
print("Password Found: {}".format(passwordChecking))
print("ATTEMPTS: {}".format(attempt))
print("TIME TO FIND: {} seconds".format(overallTimeSeconds))
wordListFile.close()
break
elif(currentLine == num_lines):
print("~~~~~~~~~~~~~~~~~")
print("Stopping Solution #1 # " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print("REASON: Password could not be cracked")
print("ATTEMPTS: {}".format(attempt))
break
else:
attempt = attempt + 1
currentLine = currentLine + 1
continue
The main problem with your code is that you open the file and you read it multiple times. The first time the file object position goes to the end and stays there. Next time you read the file nothing happens, since you are already at the end of the file.
Example
Sometimes an example is worth more than lots of words.
Take the file test_file.txt with the following lines:
line1
line2
Now open the file and read it twice:
f = open('./test_file.txt')
f.tell()
>>> 0
for l in f:
print(l, end='')
else:
print('nothing')
>>> line1
>>> line2
>>> nothing
f.tell()
>>> 12
for l in f:
print(l, end='')
else:
print('nothing')
>>> nothing
f.close()
The second time nothing happen, as the file object is already at the end.
Solution
Here you have two options:
you read the file only once and save all the lines in a list and then use the list in your code. It should be enough to replace
wordListFile = open("customPassFile.txt", encoding="utf8")
num_lines = sum(1 for line in open('customPassFile.txt'))
with
with open("customPassFile.txt", encoding="utf8") as f:
wordListFile = f.readlines()
num_lines = len(wordListFile)
you reset the file object position after you read the file using seek. It would be something along the line:
for i, line in enumerate(wordListFile):
if(i == currentLine):
line = line
wordListFile.seek(0)
I would go with option 1., unless you have memory constraint (e.g. the file is bigger than memory)
Notes
I have a few extra notes:
python starts counters with 0 (like c/c++) and not 1 (like fortran). So probably you want to set:
currentLine = 0
when you read a file, the new line character \n is not stripped, so you have to do it (with strip) or account for it when comparing strings (using e.g. startswith). As example:
passwordChecking == passwordCracking
will likely always return False as passwordChecking contains \n and passwordCracking very likely doesn't.
Disclamer
I haven't tried the code, nor my suggestions, so there might be other bugs lurking around.
**I will delete this answer after OP understands the problem in indentation of I understand his intention of his code.*
for i, line in enumerate(wordListFile):
if(i == currentLine):
line = line
passwordChecking = line
#rest of the code.
Here your code is outside of for loop so only last line is cached.
for i, line in enumerate(wordListFile):
if(i == currentLine):
line = line
passwordChecking = line
#rest of the code.

find a matching line in a txt with python

I can test whether a string is in a text file with python like the following:
if(pdfname in open(filename).read()):
//do something
But how I can I verify it? I want the matching line show up. Thanks.
You can print out the relevant lines with the second for statement below, which I've added to your existing code for illustration:
pdfname = "statementConcentrator"
if (pdfname in open("line56.good").read()):
print "Found it"
lineNum = 0
for line in open("line56.good").readlines():
lineNum = lineNum + 1
if pdfname in line:
print "#%5d: %s"%(lineNum, line[:-1])
This outputs your current line plus my output for verification:
Found it
# 115: statementConcentrator=0
and, checking that file, that is indeed the line it's found on.
Note that you can simply use a script as follows to do both jobs in a single loop:
pdfname = "statementConcentrator"
lineNum = 0
count = 0
for line in open("line56.good").readlines():
lineNum = lineNum + 1
if pdfname in line:
print "#%5d: %s"%(lineNum, line[:-1])
count = count + 1
print "Found on %d line(s)."%(count)
Just loop over the file:
handle = open(filename, 'r')
for line in handle:
if pdfname in line:
print line
handle.close()

Categories