Ok, I'm using python and tk to write a program. I need it to open a file and read one line, print it, then read the next line and print it. I first use:
self.wordlist = tkFileDialog.askopenfile(mode='rb',title='Select a wordlist')
In another part of the code I have:
num = 1
while True:
line = self.wordlist.readlines()[num].strip()
print line
num = num + 1
When I run this it returns:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Users\Owner\Desktop\hashgui.py", line 109, in hashcrack_command
line = self.wordlist.readlines()[num].strip()
IndexError: list index out of range
It prints the first line but stops on the second? Why?
The count in Python starts at 0, so it should be num = 0. The first line is at file.readlines()[0].
However, this way looks better:
for line in self.wordlist:
print line
Related
I am making a blockchain, I am storing the latest block in a file named lb.store
,but my code to open and read the file returns ''.
Here is the Error.
Traceback (most recent call last):
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 48, in <module>
recieve_request()
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 39, in recieve_request
add_block(data)
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 7, in add_block
new_block_number = int(lblock_number) + 1
ValueError: invalid literal for int() with base 10: ''
Here is the full code that caused this:
lblock_numberf = open("lb.store","a+")
lblock_number = lblock_numberf.read()
lblock_numberf.close()
new_block_number = int(lblock_number) + 1
It looks like that the file you're trying to read is either empty or the end of the string appears to be <"">. Play around the values to debug the problem
I am reading a set of coordinates from a file to produce a shape in the Python Turtle. After reading reading in the coordinates, I have written a for loop that goes through the list of coords and draws them. However, upon running with a correct file name, I get this error:
Traceback (most recent call last):
File "C:\Users\06113\Desktop\My Stuff\Python Saves\Vec Draw\Vec Draw.py", line 55, in <module>
t.goto(cs)
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 1774, in goto
self._goto(Vec2D(*x))
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 3195, in _goto
self._update() #count=True)
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 2660, in _update
self._update_data()
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 2650, in _update_data
self.screen._drawline(self.currentLineItem, self.currentLine,
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 543, in _drawline
cl.append(x * self.xscale)
TypeError: can't multiply sequence by non-int of type 'float'
Is there any way at all that I could fix this in MY file? I would rather not go into the turtle module where I could easily mess something up.
The code for this section in my file is:
t = turtle.Turtle(visible=False)
t.speed(0)
for i in range(0, len(coord_list), 2):
if i == 0 and i+1 == 1:
fcs = (coord_list[i], coord_list[i+1])
t.pu()
t.goto(fcs)
t.pd()
pass
else:
cs = (coord_list[i], coord_list[i+1])
t.goto(cs)
cs = None
pass
pass
t.goto(fcs)
print("Vector image drawn.")
I am trying to use a file to read ip addresses and then find out corresponding location of that address
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE.BIN");
#t=open('output.txt','w');
t=open('test_ip','r');
Line=t.readline();
While line:
rec = IP2LocObj.get_all(Line);
Line=t.readline();
print rec.country_short
error is coming here
Traceback (most recent call last):
File "myprogram.py", line 8, in <module>
rec = IP2LocObj.get_all(t);
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 219, in get_all
return self._get_record(addr)
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 364, in _get_record
ipv = self._parse_addr(ip)
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 357, in _parse_addr
socket.inet_pton(socket.AF_INET, addr)
TypeError: inet_pton() argument 2 must be string, not file
This code is giving error.You can check out the sample code here http://www.ip2location.com/developers/python
Please try the new Python codes below.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN"); # This is sample database
with open('test_ip.txt') as f: # file containing ip addresses
for line_terminated in f:
line = line_terminated.rstrip('\r\n'); # strip newline
if line: # non-blank lines
print line
rec = IP2LocObj.get_all(line);
print rec.country_short
My code has a file "filefile.txt" which has a compressed sentence in it. The file is laid out like :
1
2
3
4
5
1
2
6
9
10
11
2
12
12
9
This
is
a
sentence
.
too
!
Yo
yo
bling
The original text that I want to decompress says "!"
My code says:
fo = open("filefile.txt","r")
script = fo.readline()
script2 = fo.readline()
fo.close()
script2 = script2.split()
script = [s.strip("\n") for s in script]
sentencewords = []
while len(script) > 0:
for p in script:
sentencewords.append(enumerate(script2.index(p)))
script.remove(0)
print(sentencewords)
This is the error:
Traceback (most recent call last):
File "F:\Computing code attempts\AT13.py", line 46, in <module>
sentencewords.append(enumerate(script2.index(p)))
ValueError: '1' is not in list
I need sentencewords to contain "This is a sentence. This is too! Yo yo bling bling!"
I have changed it now but it still doesn't work.
sentencewords.append(enumerate(script2.enumerate(p)))
'Traceback (most recent call last):
File "F:\Computing code attempts\AT13.py", line 46, in
sentencewords.append(enumerate(script2.enumerate(p)))
AttributeError: 'list' object has no attribute 'enumerate''
Does anyone know if there is another way round this problem or how to fix my current code?
fo = open("filefile.txt","r")
script = fo.readline()
script2 = fo.readline()
fo.close()
script2 = script2.split()
script = [s.strip("\n") for s in script]
sentencewords = []
indexes = []
for line in fo:
if line.strip().isdigit():
indexes.append(line)
else:
break
words = [line.strip() for line in fo if line.strip()]
while len(script) > 0:
for p in script:
sentencewords.append(words[index-1])
print(sentencewords)
Updated code but I don't know what the I/O thing means in the latest output from python.
Traceback (most recent call last):
File "F:/Computing code attempts/attempt14.py", line 45, in <module>
for line in fo:
ValueError: I/O operation on closed file.
Any suggestions on how to fix my code, I'd be grateful for
Your code uses a file parsing while the file is close:
fo.close()
...
indexes = []
for line in fo:
You can delay the fo.close() to the end of your script and it will pass the ValueError: I/O operation on closed file.
I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
import re
def get_function_name(module, line):
module_file = module.replace('.', '/') + '.py'
lines = open(module_file, 'r').xreadlines()
i = line - 1
try:
while i:
tmp = next(lines)
i -= 1
except StopIteration:
raise EOFError('Not enought lines in module %s' % module)
function_line = next(lines)
function_name = re.match('def (\w+)\([^)]*\):', function_line)
if function_name:
return function_name.group(1)
raise ValueError('No function declared on line %s' % line)
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:
>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module