How can I tell to my code to not end and start again ?
From the 1st try:
running = True
while running:
f = open('list.txt', 'r', encoding='utf-8').readlines()
for word in f:
if word == "\n":
continue
driver.find_element_by_xpath(Newtweet_button).click()
sleep(0.5)
driver.find_element_by_xpath(message_paste).send_keys(word)
try:
driver.find_element_by_xpath(post_tweet_xpatch).click()
sleep(1)
except (ElementClickInterceptedException):
driver.find_element_by_xpath(cross_button).click()
except (NoSuchElementException):
print("tweet not send")
driver.find_element_by_xpath(cross_button).click()
sleep(4)
else:
driver.find_element_by_xpath(close_button2).click()
sleep(4)
f.close()
Use a while loop:
running = True
while running:
#your code
This won't stop until running is set to false: running = false
Or you can have a count:
count = 0
while count >= 3:
#your code
count += 1
This will make the code run 3 times.
EDIT: to close your file you need to not read the file variable, like this:
with open('list.txt', 'r', encoding='utf-8') as f:
file = f.readlines()
for word in file:
if word == "\n":
continue
Related
Anybody can advise what could be wrong with my code?
I am trying to make a method that removes the single line comments from the content.
Also, the method should return the single line comments that start with '#'.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
def deleteComment(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
This should make it work.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comments_count = 0
for i in data.split('\n'):
if i[0] == "#":
clean += i
clean += '\n'
comments_count += 1
else:
pass
name = os.path.basename(path)
with open("clean-" + name, "w") as f:
f.write(clean)
f.close()
my_file.close()
return comments_count
except:
print("An error occurred with accessing the files")
return file
I have a pickle db with 5 variable in it that goes : rafTur, rafKat, rafNo, rafIndex, rafIndexData. I'm trying to delete a data inside my pickle file. My main goal is taking an input from user that goes like this :
rafTur = S rafKat = 1 rafNo = 2 rafIndex = 3
And then finding that imput from my pickle file that named noSqlDB. and then delete the entire data about input.
def delPic():
infile = open('noSqlDB', 'rb+')
sistem = pickle.load(infile)
flag = False
rafTur = str(input('Rafın türünü giriniz : '))
rafKat = int(input('Rafın katını giriniz : '))
rafNo = int(input('Rafın Nosunu giriniz : '))
rafIndex = int(input('Rafın indexini giriniz : '))
# read to the end of file.
for x in range((len(sistem) + 1)):
try:
if (sistem['rafTur'].upper() == rafTur.upper() and sistem['rafKat'] == rafKat and sistem['rafNo'] == rafNo and sistem['rafIndex'] == rafIndex):
del sistem
flag = True
sistem = pickle.load(infile)
except EOFError:
break
if flag == False:
print('Record not Found')
infile.close()
When i run this code nothing changes. The data stays on noSqlDB. How can i delete the data inside the noSqlDB ? like this
I tried changing
del sistem
to
del sistem['rafTur'],sistem['rafKat'], sistem['rafNo'],sistem['rafIndex'],sistem['rafIndexData']
def unpickle_database(filename):
with open(filename, 'rb') as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
def save_object(obj, filename,a):
if a < 1:
with open(filename, 'wb+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
else :
with open(filename, 'ab+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def delPic():
temp =0
students = list(unpickle_database('noSqlDB'))
for student in students:
print(student)
save_object(student, 'noSqlDB',temp)
temp += 1
Found a solution after trying some code here it is.
Here is this block of code I'm trying to finish:
elif parameter == 'statistics':
outfile.write(stats(infile))
for line in infile:
outfile.write(line)
So essentially, I am trying to write the statistics of the file into the new file that is being copied. The statistics works and everything as when I open the file, the statistics are written in. However, I noticed because of the two outfile.write it seems to close after the first one, so only the statistics go in and not the rest of the content in the original file.
The error that I am getting is this:
ValueError: I/O operation on closed file.
I am unsure why the file is closing.
EDIT: Here is the whole code, as requested
def copy_file():
infile_name = input("Please enter the name of the file to copy: ")
infile = open(infile_name, 'r', encoding='utf8')
parameter = input("Please enter a parameter(line numbers, Gutenberg trim, statistics, none): ")
outfile_name = input("Please enter the name of the new copy: ")
outfile = open(outfile_name, 'w', encoding='utf8')
counter = 1
if parameter == 'line numbers':
for line in infile:
outfile.write(f' {counter:6}: {line}')
counter += 1
elif parameter == 'Gutenberg trim':
copyStart = False
for line in infile:
#print(line.strip())
if '*** START' in line.strip():
copyStart = True
continue
elif '*** END' in line.strip():
copyStart = False
break
if copyStart == True:
outfile.write(line)
elif parameter == 'statistics':
outfile.write(stats(infile))
for line in infile:
outfile.write(line)
else:
for line in infile:
outfile.write(line)
infile.close()
outfile.close()
copy_file()
EDIT2: So sorry for not including it. Here is the stats function:
def stats(text) -> str:
with text as infile:
totallines = 0
emplines = 0
characters = 0
for line in infile:
totallines += 1
characters += len(line)
if len(line.strip()) == 0:
emplines += 1
lines = totallines - emplines
totalaveChars = characters/totallines
nonempaveChars = characters/lines
result = (f'{totallines:5} lines in list \n'
f'{emplines:5} empty lines in list \n'
f'{totalaveChars:5.1f} average characters per line \n'
f'{nonempaveChars:5.1f} average chars per non-empty line')
return result
print(stats(open('ASH.txt', 'r', encoding='utf8')))
Here is the result from stats:
13052 lines in list
2666 empty lines in list
44.6 average characters per line
56.0 average chars per non-empty line
The issue is in the stats function. The with statement will close the file with the local name text, which is infile in your case!
def stats(text) -> str:
totallines = 0
emplines = 0
characters = 0
for line in text:
totallines += 1
characters += len(line)
if len(line.strip()) == 0:
emplines += 1
lines = totallines - emplines
totalaveChars = characters/totallines
nonempaveChars = characters/lines
result = (f'{totallines:5} lines in list \n'
f'{emplines:5} empty lines in list \n'
f'{totalaveChars:5.1f} average characters per line \n'
f'{nonempaveChars:5.1f} average chars per non-empty line')
return result
In your main program, you passed to the function stats the variable infile, which is a file. You do not need to reopen it with with inside the stats functions. Moreover, with will ensure the closing at the end. Thus in your main loop, the infile is closed after the call on stats.
Try the following;
def copy_file():
infile_name = input("Please enter the name of the file to copy: ")
parameter = input("Please enter a parameter(line numbers, Gutenberg trim, statistics, none): ")
outfile_name = input("Please enter the name of the new copy: ")
counter = 1
with open(infile_name, 'r', encoding='utf8') as infile:
with open(outfile_name, 'w', encoding='utf8') as outfile:
if parameter == 'line numbers':
for line in infile:
outfile.write(f' {counter:6}: {line}')
counter += 1
elif parameter == 'Gutenberg trim':
copyStart = False
for line in infile:
#print(line.strip())
if '*** START' in line.strip():
copyStart = True
continue
elif '*** END' in line.strip():
copyStart = False
break
if copyStart == True:
outfile.write(line)
elif parameter == 'statistics':
outfile.write(stats(infile))
for line in infile:
outfile.write(line)
else:
for line in infile:
outfile.write(line)
copy_file()
Using with open(filename, 'r') as file: it will automatically close the file once the operation has finished, and not before.
elif parameter == 'statistics':
outfile.write(stats(infile))
for line in infile:
outfile.write(line)
... only the statistics go in and not the rest of the content in the
original file ...
My educated guess is that the stats function consumes and possibly
closes the input stream (IS).
If stats is somehow well behaved and limits itself to consuming the
IS, one can rewind it
...
infile.seek(0) # rewind the input stream
for line in infile:
outfile.write(line)
If, on the other hand, stats is a bit disruptive and closes
altogether the IS one can use the .name attribute of the file object
to reopen it, like this
...
for line in open(infile.name):
outfile.write(line)
This second solution works even in the first, milder hypotesis and
works even if the code was passed the infile file object from a
outer call.
Another possibility, if you can access and modify the stats source
code, is to undo the reading performed by the function, memorizing
the current position in the input stream before any read operation
and later rewind the IS to that position
def stats(infile):
...
current_pos = infile.tell()
# do your stuff
...
infile.seek(current_pos)
return workload
For this to work, of course, the file object has not to be closed
before the .seek(), either explicitly (by a .close()) or
implicitly (by falling outside the scope of a with block).
If this is your situation (closed file), please remove either the
explicit infile.close() or the (unnecessary) with statement and
the rewind will be correct.
I want to make a limit (say three times) to the attempts when trying to open file and the file cannot be found.
while True:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
except FileNotFoundError:
print ('File does not exist')
print ('')
else:
break
The result of the code above, there is no limit. How can I put the limit in the above codes.
I am using python 3.5.
Replace while True: by for _ in range(3):
_ is a variable name (could by i as well). By convention this name means you are deliberately not using this variable in the code below. It is a "throwaway" variable.
range (xrange in python 2.7+) is a sequence object that generates (lazily) a sequence between 0 and the number given as argument.
Loop three times over a range breaking if you successfully open the file:
for _ in range(3):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
break
except FileNotFoundError:
print ('File does not exist')
print ('')
Or put it in a function:
def try_open(tries):
for _ in range(tries):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename, "r", newline='')
return inputfile
except FileNotFoundError:
print('File does not exist')
print('')
return False
f = try_open(3)
if f:
with f:
for line in f:
print(line)
If you want to use a while loop then the following code works.
count = 0
while count < 3:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
count += 1
except FileNotFoundError:
print ('File does not exist')
print ('')
So I am trying to write a piece of code to take text from a file, move into a dictionary and then process it. I keep getting this error:
File "C:\Users\Oghosa\Assignment2.py", line 12, in <module>
builtins.IndexError: string index out of range
Here's my program:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
Can someone aid in pointing out my mistake please?
Here's a sample input text:
#Comments
a01:01-24-2011:s1
a03:01-24-2011:s2
<blank line>
<blank line>
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
<blank line>
#comments
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
Well, you should at least print the offending line so you know what the culprit is:
for line in infile:
items = line.strip("\n")
try:
if (line.strip != "") and (items[0] != "#"):
items = line.split(":") #i dont like your reuse of line so changing to items
....
except IndexError: #if python 3 use except IndexError as e:
print(items) #prints offending line
endofprogram = False
attrs=["Animal id","Date","Station"]
dictionary=[]
try:
# filename = input("Please Enter the Filename:")
infile = open('rite.txt', 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != "") and (line[0] != "#"):
item = line.split(":")
dictionary.append(dict(zip(attrs, item)))
print dictionary
Your problem is that when there are blank lines in the file, line[0] doesn't exist. To fix this problem try this version:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if len(line):
if line[0] != "#":
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
Also worth noting is that you are overwriting dic on each iteration of the loop. So after the loop is done; dic will only contain information from the last line of the file.
The problem is you weren't checking for empty lines correctly in the
if (line != " ") and (line[0] != "#"):
statement. This is because they wouldn't even have a space left in them after line = line.strip("\n") executed, so just about any indexing operation will fail.
The code below has that and several other coding errors fixed. Note it's important to post your actual code here to make it easier for people to help you.
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if not endofprogram:
for line in infile:
line = line.strip("\n")
if line and line[0] != "#":
items = line.split(":")
print(items)
dic["Animal id"] = items[0]
dic["Date"] = items[1]
dic["Station"] = items[2]
print(dic)
Do you have a blank line in your file? On line 12 you may want to check that the line has text before indexing it using line[0]. Do you really have a line with an empty string of should line 12 really read:
if line.strip() and (line[0] != "#"):
Edit.. Adding a full example.
dic = {}
filename = input("Please Enter the Filename:")
try:
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
else:
for line in infile:
line = line.strip()
if line and line[0] != "#":
item = line.split(":")
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]