How to decompress a file - python

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.

Related

Why does file.read() return '' in python

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

EOFError: Ran out of input when unpickling non-empty file

Traceback (most recent call last):
File "C:\Users\me\folder\project.py", line 999, in <module>
load_data()
File "C:\Users\me\folder\project.py", line 124, in load_data
globals()[var_name] = pickle.(f)
EOFError: Ran out of input
I get this error when trying to unpickle a file, even though the file is non-empty. I've tried opening the file and printing its value and it is non-empty, but the unpickler returns this result still.
Anyone know why this may be happening?
The code here is as follows:
files_to_load = ['var1','var2',...]
def load_data():
for var_name in files_to_load:
path = '{}.txt'.format(var_name)
if os.path.exists(path):
with open(path, 'rb') as f:
globals()[var_name] = pickle.Unpickler(f).load()
else: globals()[var_name] = {}

ip2location python library error

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

Python Tk IndexError:list index out of range

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

Getting function containing a line in Python

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

Categories