First, code gets a name and makes a file with w permission (also tested r+) and it should write any other input in file, but it doesn't. I get an empty file.
user_name_in =input("gets Input")
fname = user_name_in
f = input()
ufile = open(fname,"w")
while True:
f=input(answer)
ufile.write(f)
As i wrote in the comments, always use the with block to handle files as it takes care of intricacies you don't have to worry about. Now on the code, you repeat yourself, for example the first two lines are actually one.. This is what it would look when cleaned a bit.
fname = input("gets Input")
with open(fname, "w") as ufile:
f = input('write something')
ufile.write(f)
And as others also noticed, the answer is never declared, there is no termination condition and the input prompts are either not the best or totally absent.
This code works for me:
user_name_in =input("gets Input")
fname = user_name_in
f = input()
ufile = open(fname,"w")
while True:
f=input(answer)
ufile.write(f)
Some considerations:
I don't see where answer is declared, neither python interpreter see :P, maybe you forgot to paste this part of the code or indeed this was the error?
I don't understand why you assign the name of the file to a variable and then re-assign to another one.
How do I stop writing to the file? The only way I found was Ctrl-C, which doesn't sound ideal.
To reassure the file is being closed you can replace it with a with open(fname) as ufile block
Related
I'm making a program to find out how many times something appears in a file (which will be read by Python) - my first step (just to make sure wha I'm doing is correct) is to see the whole file opened in Python.. if you get me?
def input_function():
my_file = open("ChoralShieldData.csv", "r")
ChoralShieldData = []
for each_line in my_file:
ChoralShieldData.append(each_line.split())
return ChoralShieldData
#Main program
ChoralShieldData = input_function()
Thank you in advance
Neither you print the result nor you write the result in your file. That's why you can't see any result.
You haven't told the code to show you anything. At the moment all it is doing is storing the data in your variable ChoralShieldData.
Try adding this to the very bottom of your code (pick one only):
print ChoralShieldData #Python 2.x
print(ChoralShieldData) #Python 3.x
Alternatively, add a similar print statement anywhere in your function to see what it is doing at specific stages.
See here for some more help on reading from and writing to files.
Noob question here. I'm scheduling a cron job for a Python script for every 2 hours, but I want the script to stop running after 48 hours, which is not a feature of cron. To work around this, I'm recording the number of executions at the end of the script in a text file using a tally mark x and opening the text file at the beginning of the script to only run if the count is less than n.
However, my script seems to always run regardless of the conditions. Here's an example of what I've tried:
with open("curl-output.txt", "a+") as myfile:
data = myfile.read()
finalrun = "xxxxx"
if data != finalrun:
[CURL CODE]
with open("curl-output.txt", "a") as text_file:
text_file.write("x")
text_file.close()
I think I'm missing something simple here. Please advise if there is a better way of achieving this. Thanks in advance.
The problem with your original code is that you're opening the file in a+ mode, which seems to set the seek position to the end of the file (try print(data) right after you read the file). If you use r instead, it works. (I'm not sure that's how it's supposed to be. This answer states it should write at the end, but read from the beginning. The documentation isn't terribly clear).
Some suggestions: Instead of comparing against the "xxxxx" string, you could just check the length of the data (if len(data) < 5). Or alternatively, as was suggested, use pickle to store a number, which might look like this:
import pickle
try:
with open("curl-output.txt", "rb") as myfile:
num = pickle.load(myfile)
except FileNotFoundError:
num = 0
if num < 5:
do_curl_stuff()
num += 1
with open("curl-output.txt", "wb") as myfile:
pickle.dump(num, myfile)
Two more things concerning your original code: You're making the first with block bigger than it needs to be. Once you've read the string into data, you don't need the file object anymore, so you can remove one level of indentation from everything except data = myfile.read().
Also, you don't need to close text_file manually. with will do that for you (that's the point).
Sounds more for a job scheduling with at command?
See http://www.ibm.com/developerworks/library/l-job-scheduling/ for different job scheduling mechanisms.
The first bug that is immediately obvious to me is that you are appending to the file even if data == finalrun. So when data == finalrun, you don't run curl but you do append another 'x' to the file. On the next run, data will be not equal to finalrun again so it will continue to execute the curl code.
The solution is of course to nest the code that appends to the file under the if statement.
Well there probably is an end of line jump \n character which makes that your file will contain something like xx\n and not simply xx. Probably this is why your condition does not work :)
EDIT
What happens if through the python command line you type
open('filename.txt', 'r').read() # where filename is the name of your file
you will be able to see whether there is an \n or not
Try using this condition along with if clause instead.
if data.count('x')==24
data string may contain extraneous data line new line characters. Check repr(data) to see if it actually a 24 x's.
I have this function:
def read_file(fname):
f = open(fname, 'r')
s = f.read()
return s
It is supposed to take an input(the name of the file to read) and save it to a variable called portfolio. However, if I specify a file that does not exist, I get an IOError, and I can't seem to figure out how to deal with it through try/except.
Any ideas?
You can't stop it from giving you the IOError for a nonexistent file. If you could, how would you even know that you had to do anything, like ask for another filename?
What you can do is deal with that error—in any way you want, like asking for another filename.
For example:
while True:
fname = raw_input('Gimme a filename')
try:
contents = read_file(fname)
break
except IOError as e:
print('Sorry, {} gives me an error: {}'.format(fname, e))
Now, when you run this, it'll keep asking for a filename until you give it one that you can read. If you give it a file that doesn't exist (or one that you don't have read permissions for, or that's locked for exclusive access, or that's stored on a bad disk block, or anything else that can cause an error), it'll ask you again.
Why not just do this?
success = 0
while (success == 0):
try:
#get your input
read_file(fname)
success = 1
except(IOError):
success = 0 #totally unnecessary I guess, but whatever
It's been a while since I did real development, so that might not be how try/except actually works in Python, but you get the idea.
Is it possible to define a variable as open("file.txt", "a") and call it more than once so you don't have to keep typing open("file.txt", "a")?
I tried, but it doesn't seem to work for me. I keep getting the error message:
ValueError: I/O operation on closed file.
My code looks like:
x = open("test.txt", "a")
with x as xfile:
xfile.write("hi")
#works fine until I try again later in the script
with x as yfile:
yfile.write("hello")
Question: Is there a way to do this that I'm missing?
(My apologies if this question is a repeat, I did search google and SO before I posted a new question.)
If you don't want to close the file right away, don't use a with statement and close it yourself when you're done.
outfile = open('test.txt', 'w')
outfile.write('hi\n')
x = 1
y = 2
z = x + y
outfile.write('hello\n')
outfile.close()
Typically you use the with statement when you want to open a file and do something with that file immediately, and then close it.
with open('test.txt', 'w') as xfile:
do something with xfile
However, it is best practice to take care of all your I/O with a single file at once if you can. So if you want to write several things to a file, put those things into a list, then write the contents of the list.
output = []
x = 1
y = 2
z = x + y
output.append(z)
a = 3
b = 4
c = a + b
output.append(c)
with open('output.txt', 'w') as outfile:
for item in output:
outfile.write(str(item) + '\n')
The with statement closes the file automatically. It is good to do everything related to the file inside the with statement (opening a file multiple times is also not a good idea).
with open("test.txt", "a") as xfile:
# do everything related to xfile here
But, if it doesn't solve your problem then don't use the with statement and close the file manually when the work related to that file is done.
From docs:
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.
You example doesn't make much sense without more context, but I am going to assume that you have a legitimate need to open the same file multiple times. Answering exactly what you are asking for, you can try this:
x = lambda:open("test.txt", "a")
with x() as xfile:
xfile.write("hi")
#works fine until I try again later in the script
with x() as yfile:
yfile.write("hello")
The usual way to use with statements (and indeed I think the only way they work) is with open("text.txt") as file:.
with statements are used for handling resources that need to be opened and closed.
with something as f:
# do stuff with f
# now you can no longer use f
is equivalent to:
f = something
try:
# do stuff with f
finally: # even if an exception occurs
# close f (call its __exit__ method)
# now you can no longer use f
I must have skipped a page or two by accident during my PDF Tutorials on Python commands and arguments, because I somehow cannot find a way to take user input and shove it into a file. Don't tell me to try and find solutions online, because I did. None made sense to me.
EDIT: I am using Python 3.1.2, sorry for forgetting
Solution for Python 3.1 and up:
filename = input("filename: ")
with open(filename, "w") as f:
f.write(input())
This asks the user for a filename and opens it for writing. Then everything until the next return is written into that file. The "with... as" statement closes the file automatically.
Solution for Python 2
Use raw_input() to take user input. Open a file using open() and use write() to write into a file.
something like:
fd = open(filename,"w")
input = raw_input("user input")
fd.write(input)
Try Something Like This.
#Getting Where To Save File
where = raw_input('Where Do You Want To Save Your File? ')
#Getting What To Write To File
text = raw_input('What Do You Want To Write To Your File? ')
#Actually Writing It
saveFile = open(where, 'w')
saveFile.write(text)
saveFile.close()
Try this out as this also places your input lines each on a new line.
filename = "temp.txt"
with open(filename, "w") as f:
while True:
try:
f.write(input())
f.write("\n")
except EOFError:
break