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:\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:\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:/code attempts/attempt14.py", line 45, in <module>
for line in fo:
ValueError: I/O operation on closed file.
fo.close() has been moved further down the code and now it says
Traceback (most recent call last):
File "F:\code attempts\attempt14.py", line 55, in <module>
sentencewords.append(words[index-1])
MemoryError
Any suggestions on how to fix my code, I'd be grateful for
thanks
Format the text file in a better way and it will be easier to deal with.
1 2 3 4 5 1 2 6 9 10 11 2 12 12 9
This is a sentence. too ! Yo yo bling
Then do this...
script = []
sentencewords = []
with open("filefile.txt", "r") as fo:
for line in fo:
script.append(line.strip("\n").split(" "))
for i in script[0]:
sentencewords.append(script[1][int(i)-1])
print(sentencewords)
Your indices above 10 will give issues though, because you don't have that many words.
Related
So I'm trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.
letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
create_letter = open(f"{name}.txt", "w")
for line in letter:
line = line.replace("[name],", f"{name},")
create_letter.write(line)
create_letter.close()
I get the error message
Traceback (most recent call last):
File "C:\Users\Default User\PycharmProjects\Mail Merge Project Start\main.py", line 10, in <module>
create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aang\n.txt'
Is there a problem with the way I am creating the files?
You can't have newlines in your file name. It is invalid in your OS/filesystem.
Remove them with:
open(f"{name.strip()}.txt", "w")
Or:
open(f"{name.replace('\n', '')}.txt", "w")
I am reading a text file ( 20 + lines) and doing a find and replace at multiple places in the text with the below code .
with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
finds = 'MI'
pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
textdata = fp.read()
line = re.sub(pattern,'MICHIGAN',textdata)
fp.write(line)
When trying to write it back to the same file, I get the below error.
IOError Traceback (most recent call last)
<ipython-input> in <module>()
6 line = re.sub(pattern,'MICHIGAN',textdata)
7 print line
----> 8 fp.write(line)
9
what is that I am doing wrong.
You've already read the file in so you're at the end of the file and there's nowhere to write the text to.
You can get around this by going back to the beginning of the file with fp.seek(0)
Also surrounding whitespace is being consumed by the regex so you can add it back in.
So your code would be:
with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
finds = 'MI'
pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
textdata = fp.read()
line = re.sub(pattern,' MICHIGAN ',textdata)
fp.seek(0)
fp.write(line)
td = 'date of transaction.txt'
tf = 'current balance.txt'
tr = 'transaction record.txt'
for line in open(tf):pass
for line2 in open(td):pass
for line3 in open(tr):pass
print line2,line,line3
"""
so call recall back last record
"""
rd=raw_input('\ndate of transaction: ')
print "Choose a type of transaction to proceed... \n\tA.Withdrawal \n\tB.Deposit \n\tC.Cancel & exit"
slc=raw_input('type of transaction: ')
i=1
while (i>0):
if slc=="A" or slc=="B" or slc=="C":
i=0
else:
i=i+1
slc=raw_input('invalid selection, please choose again...(A/B/C): ')
if slc=="A":
rr=input('\namount of transaction: ')
Line_len = 10 # or however long a line is, since in my example they all looked the same
SEEK_END = 2
file = open(tf, "r")
file.seek(-Line_len, SEEK_END)
a = int(str(file.read(Line_len)).split(" ")[0].strip())
rf=a-rr
f1=open(tf, 'a+')
f1.write('\n'+rf)
f1.close()
d1=open(td, 'a+')
d1.write('\n'+rd)
d1.close
r1=open(tr, 'a+')
r1.write('\n-'+rr)
r1.close
else:
print 'later'
above is my code, the function is to get data(last line) from txt file and read it, get new data and write it to the txt file again by creating new line.
my txt file(current balance.txt) should look like this:
2894.00
2694.00
but when i try to use the last line which is 2694.00 to do calculation(rf=a-rr), it failed returning this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
file.seek(-Line_len, SEEK_END)
IOError: [Errno 22] Invalid argument
else if i use this code:
for line in open(tf):
pass
a = line
rf=a-rr
it return this error:
Traceback (most recent call last):
File "C:\Python27\acc.py", line 27, in <module>
rf=a-rr
TypeError: unsupported operand type(s) for -: 'str' and 'int'
I seriously have no idea why...please help me...
To obtain last line of the file, you can simple do
with open('my_file.txt') as file:
last_line = file.readlines()[-1]
#last_line is a string value pointing to last line, to convert it into float, you can do
number = float(last_line.strip('\n').strip(' '))
The function input is giving you a string. Try doing:
rf=a-float(rr)
I have a problem when I use this code to count the number of pages in pdf file :
if j[i].rstrip() == "Page" or j[i].rstrip() == "page":
rxcountpages = re.compile(r"/Type\s*/Page([^s]|$)", re.MULTILINE|re.DOTALL)
data = file("/home/suleiman/Desktop/CVE-2011-2462_36EE5F9C51316E060657AA86D48670E8","rb")
print len(rxcountpages.findall(data))
the error is:
Traceback (most recent call last):
File "pdf_scanner.py", line 89, in
main()
File "pdf_scanner.py", line 72, in main
print len(rxcountpages.findall(data))
TypeError: expected string or buffer
can an one help me with it?
you have to read the contents of the file:
data = open("/home/suleiman/Desktop/CVE-2011-2462_36EE5F9C51316E060657AA86D48670E8","rb").read()
I have a problem, I need the help of everyone.
I read rar file (100mb) and process text file (include in rarfile).
import glob
import os
import UnRAR2
from os import path, access, R_OK
os.chdir("E:\\sms")
for file in glob.glob("*.rar"):
# extract test.txt to memory
entries = UnRAR2.RarFile(file).read_files('*.txt')
test_content = entries[0][1]
#print test_content
for line in test_content.split("\n"):
A=line.split(' ')
print A[1]
Result:
19009057
7030
9119
9119
....
....
bla...bla...
......
9119
9119
9119
7050
9119
Traceback (most recent call last):
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:\Users\The\Documents\workspace\unrar\test_unrar.py", line 13, in <module>
print A[1]
IndexError: list index out of range
Please, help me!
Thank you!!!
One of your lines (probably your last) is not in the format you expect. Do this in your inner for loop:
A=line.split(' ')
if len(A) > 1:
print A[1]
A[1] would be suspect if the last line in your file was \n. You'd want to rethink the way you're pulling info back.
The error is telling you that the content of line split up, A, doesn't have a second item, which means that it doesn't have anything left to parse, and you're at the end of the file.