So I have this code, and I am trying to have it open a file. However, the exception part of the code always gets executed.
def main():
#Opens up the file
try:
fin = open("blah.txt")
independence = fin.readlines()
fin.close()
independence.strip("'!,.?-") #Gets rid of the punctuation
print independence
#Should the file not exist
except:
print 'No, no, file no here'
if __name__ == "__main__":
main()
I checked to see if the file name was spelled correctly, and it was, and the file is in the same directory as the python file, and I've used this code before. Why is it not working?
independence is a list of strings. You can't call strip on a list.
Try this:
def main():
fin = open('blah.txt', 'r')
lines = fin.readlines()
fin.close()
for line in lines:
print line.strip("'!,.?-")
if __name__ == '__main__':
try:
main()
except Exception, e:
print '>> Fatal error: %s' % e
Related
I have a script here to check for an error, and I want to make it so that if it doesn't find one it runs the for loop again. What do I add after the last line?
with open("apacheErrorLog.rtf","r")as f_obj:
lines = f_obj.readlines()
for line in lines:
print(line.rstrip())
try:
with open("apacheErrorLog.rtf","r")as f_obj:
lines = f_obj.readlines()
except FileNotFoundError:
print(f_name , "not found")
else:
for line in lines:
Try this. I don't think you actually want to start the loop until after you have checked if the file exists.
def main():
try:
with open("apacheErrorLog.rtf","r")as f_obj:
lines = f_obj.readlines()
except FileNotFoundError:
print(f_name , "not found")
return
for line in lines:
print(line.strip())
main()
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
Here I want to read something in a .txt file and then erase content and delete it. But it always shows it cannot delete it as 'The process cannot access the file because it is being used by another process'.
Actually what I need is to delete the .txt file, but it cannot delete immediately sometimes, so I erase the content at first in case that it will be read again. So is there any good way to read something in a .txt file and then delete this file as soon and stable as possible?
You should NOT call f.close() nor g.close(). It is called automatically by with statement.
remove the unnecessary close() statements to start - like #grapes mentioned - why are you truncating what you are deleting? just delete it...
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
exec(s)
except Error as e:
print(e)
else:
os.remove(masterpath)
FYI, it is bad form to execute the contents of a file if you do not control the contents of said file.
another option:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
try:
s = f.read()
except Error as e:
print(e)
else:
exec(s)
os.remove(masterpath)
Try to use short sleep in exception part:
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
except WindowsError:
time.sleep(sleep)
else:
break
Another way is to use:
os.remove(masterpath)
I'm trying to run the following python code for to exercise
#!/bin/python3
import os
import sys
#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
return n+1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
fptr.write(str(result) + '\n')
fptr.close()
but i get this error message
Traceback (most recent call last):
File "maximumdraws.py", line 13, in <module>
fptr = open(os.environ['OUTPUT_PATH'], 'w')
File "/home/inindekikral/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'OUTPUT_PATH'
My Operation System is Linux Mint 19 Cinnamon.
What i have to do?
I'm sure there are other ways to do this, but for Hackerrank exercises, the file pointer was opened this way:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
... and I want it to just go to standard output.
I just changed that line to
fptr = sys.stdout # stdout is already an open stream
and it does what I want.
Note that on the one hand, os.environ['OUTPUT_PATH'] is a string, while fptr is a stream/file pointer.
Variations:
If you want to write to a file, you can do it the way suggested above (setting the OUTPUT_PATH environment variable).
Or, you can set the os.environ directly in python, e.g.
os.environ['OUTPUT_PATH'] = 'junk.txt' # before you open the fptr!
os.environ lets you access environment variables from your python script, it seems you do not have an environment variable with name OUTPUT_PATH. From the terminal you run your python script, before running your python code set an environment variable with name OUTPUT_PATH such as:
export OUTPUT_PATH="home/inindekikral/Desktop/output.txt"
Your python script will create a file at that location.
A KeyError means that an element doesn’t have a key. So that means that os.environ doesn’t have the key 'OUTPUT_PATH'.
Simply, change the path of the python code to your local path.
fptr = open("./result.output", 'w')
Hackerrank sends output to a file, but for practice locally, the output can be printed.
You can remove the use of ftpr by commenting out these lines
fptr = open(os.environ['OUTPUT_PATH'], 'w') and
fptr.close()
And replace line fptr.write(str(result) + '\n') with print(str(result) + '\n')
change your code like this:
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
print(str(result) + '\n')
So i have been fiddling around with python and league of legends. And i found out you can make notes in game. So i thought about making python code read a line of text from the note i made in game, like "Lux no flash", but it doesn't seems to be able to read it at all, it only works when i do it manually with the exact same code. Here is my code:
import os
import time
def main():
os.chdir('C:\\Riot Games\\League of Legends\\RADS\\solutions\\lol_game_client_sln\\releases\\0.0.1.237')
f=open("MyNotes.txt", "r")
if f.mode == 'r':
lines=f.readlines()
text = lines[4]
time.sleep(0.1)
if text == 'Lux no flash':
print('Done')
else:
print('Something went wrong')
f.close()
if __name__== "__main__":
main()
The output is "something went wrong", but when i do it manually it says "done". I feel like python cant read league code. Maybe you guys know how to do this... This is the .txt file im trying to access:
##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash
Using lux.txt:
##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash
Code:
content = []
with open('lux.txt', 'r') as f:
for line in f:
content.append(line.strip('\n'))
for i in content:
if 'Lux no flash' == i:
print("Done")
else:
pass
Better #pygo
with open('lux.txt', 'r') as f:
content = f.read()
if 'Lux no flash' in content:
print("Done")
else:
print("No else, this works :)")
Output:
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 lux.py
Done
I'm Just taking a file on an assumption basis:
# cat MyNotes.txt
there is Lux no flash in line
there is Something went wrong
There is nothing lux no flash
this is all test
So, just looking for the word 'Lux no flash' you are searching into your file, we can simply do as below.. but its case sensitive.
It's always best practice to use with open() method to read a file.
import os
import time
def main():
with open("MyNotes.txt") as f:
for line in f.readlines():
if 'Lux no flash' in line:
print('Done')
else:
print('Something went wrong')
if __name__== "__main__":
main()
Output result will be :
Done
Something went wrong
Something went wrong
Something went wrong
Even tried using the lux.txt , it works as expected with my code.
import os
import time
def main():
with open("lux.txt") as f:
for line in f.readlines():
#line = line.strip() # use can use the strip() or strip("\n")
#line = line.strip("\n") # if you see white spaces in the file
if 'Lux no flash' in line:
print('Done')
else:
pass
if __name__== "__main__":
main()
Resulted outout is:
# test.py
Done
The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)