The aim of the following snippet of code is to search through a text file, and look for the variable 'name'. If 'name' is present anywhere in the text file, it should set user_new to False. Otherwise, it is non-existent in the txt file, and user_new should be True.
However, user_new, in both cases, is never set to anything, and results in the error: "local variable 'user_new' referenced before assignment"
with open("accuracy.txt", "r") as search:
lineno = 0
for line in search:
lineno = lineno + 1
if name in line:
user_new = False
break
else:
user_new = True
break
search.close()
print(user_new)
The only way this could happen in this code is if the for loop has nothing to iterate over. This would mean the if statement is never run and user_new is never defined.
Make sure accuracy.txt has at least one line, otherwise the loop will never run as there are no lines to loop through.
If having no lines in the text file is unavoidable, consider checking the length of the file with something such as:
if search.read() == "":
user_new = False
Issue was at times accuracy.txt was empty, which caused the loop to never run and user_new to never be defined. Thanks to #Joe Allen for the answer.
Related
>>> while True:
... line = input('> ')
... if line == 'done' :
... break
... print(line)
... print( 'Done!' )
File "<stdin>", line 6
print( 'Done!' )
^^^^^
SyntaxError: invalid syntax**
For python 3 this code should give me a "Done!" response when the break statement "done" is reached. However, I keep getting a syntax error for the last line. I have tried to do it multiple ways and I can get the break order to work without the last statement, however, it never works where I include the last statement "print('Done!')" with the break statement done. I apologize, this is just simple code but I can't seem to get it to work. Ps, I fixed it to make it as I am supposed to be writing it, the while True statement was not supposed to be twice (my error in copying it here) along with the extra space on the fifth line. and I have tried
It's not the language, it's your IDE. It is only expecting a single statement and the lines that are subordinate to it, i.e. indented. Once you've reached the end of the indenting it expects a blank line and doesn't know what to do when you try to give another statement.
If that same sequence were part of a file it would do exactly what you expect. If you put it all into a function, the whole function body will be indented and that would work too.
I am trying to read each line in proc.stdout.readline and send the lines over the network, for example:
data = b''
for line in iter(proc.stdout.readline, ''):
data += line
clientsocket.send(data)
When I run this code I seem to be stuck in a inifinite loop unable to escape to the line:
clientsocket.send(data)
Is there a more efficient way to read the data? I've tried also with a while loop and breaking 'if not line':
data = b''
while True:
line += proc.stdout.readline()
data += line
if not line:
break
clientsocket.send(data)
This seems to also produce the same results. Is there a more efficient way to read all of the data from proc.stdout.readline?
I've encountered the same very problem. The strange thing that in Python 2.7 it had no problem to converge and actually stop iterating.
During debug (in Python 3.5) I've noticed that all true lines returned with the '\n' character, whereas the line that wasn't suppose to arrive returned as an empty string, i.e. ''. So, I just added an if-clause checking against '' and breaking the loop if positive.
My final version looks as follows:
lines = []
for _line in iter(process.stdout.readline, b''):
if _line == '':
break
lines.append(_line)
One thing that might be worth to mention, is that I used universal_newlines=True argument upon subprocess.Popen(..) call.
The statement: iter(proc.stdout.readline, "") will do a blocking read until it recieves an EOF.
If you want to read all the lines, then you can just do:
data = b''
data = b"".join(proc.stdout.readlines())
There is no other solution than for the proc to produce lines faster.
If you want, you can read lines with timeout (i.e. you can wait to read a select number of characters, or timeout if that number of characters are not read).
Those answers can be found here:
https://stackoverflow.com/a/10759061/6400614 .
https://stackoverflow.com/a/5413588/6400614
I am creating a piece of code which reads in a file, assigns each line to variable 's', and evaluates whether the 'activity' column of each line of that file contains 'substr_neg', which is assigned to a '-' character.
If this character is true, then I fulfil the conditions and call a function to the 'name' column of that same line.
If false, I go to the next line.
(Just to clarify, this conditional statement is meant to see if characters in substr_neg is present in 'ss', if it is, then 'do something', else, go to next line in that file).
However, the problem is, is that the 'if not' statement conditions do not appear to be fulfilled, hence variable 'v' does not get assigned to the result of function 'foofoo'.
Also:
if not(foo)
is meant to represent a function which searches whether a string value already exists within the text file, if not, it applies the function to the name column of the file.
Does anyone have any suggestions as to why the conditions of the 'if not' statement are not being fulfilled? Perhaps scope reasons? Removing the
if (char in substr_neg for char in ss):
along with the elif statement solves all problems...but obviously this is not what I am looking for.
substr_neg ='-'
var = 'str'
char = ''
with open("file.txt") as file:
for lines in file:
if not lines.startswith("#"):
s = lines
ss = s.split('\t')
if (char in substr_neg for char in ss):
name = ss[0];
activity = ss[2];
varvar ="str".format(var,
name)
else:
next(file)
if not foo(varvar):
v = foofoo(name)
foofoofoo(v)
break;
The file variable is not a List, to turn it to a List:
file_list = file.readlines()
#Then loop through file_list
for lines in file_list:
#...
Okay, I am building a little program that will help single out Nmap results:
#Python3.7.x
#
#
#
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.1"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "Network Distance:"
for num1,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(begins) and line.endswith(target_ip):
print(num1)
for num2,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(beginsend):
print(num2)
In my what im trying to do is get the first part of the scan results "target_ip" and with that i hope i can read the lines from there until there is a break in the line of the txt.
What this code does for me now is just get me the line number where i want to start.
In the second part of the code I tried getting the number of line for the last bit of text that i need. But it wont print. Im not sure if im going about this the right way or im not looking hard enough.
In short find my line and print until there is a break in the text.
The first loop exhausts all the lines in the file. When the second loop tries to run, there are no more lines to read and the loop exits immediately.
If you want the first loop to stop when it finds a matching line and allow the second loop to read the remaining lines, you can add a break statement in the if.
start_pattern = 'hello there'
end_pattern = 'goodblye now'
print_flag = False
with open('somefile.txt') as file:
for line in file:
if start_pattern in line:
print_flag = True
if print_flag:
print line
if end_pattern in line:
break
I am writing a "simple" little program for a class i am taking. this is supposed ask me for what team to search for and then return the number of times it appears on the list in a .txt file. it requests input like it should and seems to run great! its been running for an hour now :) i am getting no errors at all it seems to be stuck in a loop.
thank you all in advance for your help!
here is my code
count = 0
def main():
# open file
teams = open('WorldSeriesWinners.txt', 'r')
# get input
who = input('Enter team name: ')
#begin search
lst = teams.readline()
while lst != '':
if who in lst:
count += 1
teams.close()
print(count)
main()
You don't need to go through the file counting lines manually. You can just use .read():
count = lst.count(who)
The other problem is that you're calling teams.close() and print(count) outside of the function.
That means they'll try to execute before you call main, and you're trying to close 'teams' which hasn't been opened or defined yet, so your code doesn't know what to do. The same is with printing count - count hasn't been defined outside of the function, which hasn't been called.
If you want to use them outside the function, at the end of the function you need to return count
Also, in your loop, you're executing the statement count += 1 which means count = count + 1, but you haven't told it what count is the first time it runs, so it doesn't know what it should add to one. Fix this by defining count = 0 before the loop inside the function.
And the reason you have an infinite loop is because your condition will never be satisfied. Your code should never take an hour to execute, like, pretty much never. Don't just leave it running for an hour.
Here's some alternative code. Make sure you understand the problems though.
def main():
file = open('WorldSeriesWinners.txt', 'r').read()
team = input("Enter team name: ")
count = file.count(team)
print(count)
main()
You can literally put this entire program into one line:
print(open('WorldSeriesWinners.txt', 'r').read().count(input("Enter team name: ")))
According to the docs :https://docs.python.org/3/library/io.html#io.IOBase.readline, readline returns single line, so in your program you have infinite loop with first line of the file
while lst != ''
You can try something like
for line in teams:
if who in line:
count += 1
If you don't mind lowercase or uppercase, you can use this modified version of #charles-clayton response!
print(open('WorldSeriesWinners.txt', 'r').read().lower().count(input("Enter team name: ").lower()))