I have created a certain function that is printing text through "print".
i want to store that prompt to a text file.
the function name is "printall(x)".
I have tried the following
text_file = open('newfile.txt', 'w')
text_file.write(printall(x))
text_file.close
this did not work.
how can I make it happen?
Thanks
First, do: import sys at the top of your code.
Then, in your printall(x) method, you should add the following as your first line:
sys.stdout = open('newfile.txt', 'w')
Then, whenever you do print, it will write the code to the file instead of the console.
Hope that helps.
Related
I tried to write the results in the text file. When I am printing the results I can be able to result but when I am moving the result I cannot see in the text file.
Here is the code that I have written
with open ('file.txt', 'r') as fp:
line = fp.readline(1)
while line:
line = fp.readline()
a=len(line)
b=line.find('The',0,a)
c=line.find('are',0,a)
b= b+4
b1=str(line[b:b+7])
c=c+4
c1=str(line[c:c+7])
var = ' '
var = "".join([b1, c1])
var1=str(var)
print (var)
with open ('new.txt', 'w') as file:
file.write(var)
result that I am seeing when printing but in the text file. Appending the text is working but I do not want to append the text every time I execute. I just want only once even if I execute n times.
eating mango
Help me where I am going wrong. Any help would be appreciated. Thank you
You need to call file.write, not just assign it to a variable:
with open ('new.txt', 'w') as file:
file.write (var)
Could this be what you need:
v = ''
with open ('file.txt', 'r') as fp:
line = fp.readline(1)
while line:
line = fp.readline()
a=len(line)
b=line.find('The',0,a)
c=line.find('are',0,a)
b= b+4
b1=str(line[b:b+7])
c=c+4
c1=str(line[c:c+7])
var = ' '
var = "".join([b1, c1])
var1=str(var)
v+=var+'\n'
with open ('new.txt', 'w') as file:
file.write(v)
think this might be this issue
file = file.write (var)
you're assigning it to a variable instead of just calling it, should be:
file.write(var)
also in the future if you plan on outputting several lines of code to a file, look into using the logging module ;) https://docs.python.org/3/library/logging.html
I've come up with two issues with your code.
1) Assigning file to the new file
Don't use the code file = file.write(var). Instead what you would want is: file.write(var)
2) File is already a built in
You shouldn't use this variable name, as it is already built in to python. Name the variable f or something else.
Here's a working example on repl.it Writing To A File.
Please comment if there are any other problems or questions.
I have a python script 'main.py' which calls another python script called 'getconf.py' that reads from a file 'configuration.txt'. This is what it looks like:
if __name__ == "__main__":
execfile("forprolog.py") # this creates configuration.txt
execfile("getconf.py")
When getconf.py is called via main.py it sees configuration.txt as an empty file and fails to read the string from it.
This is how I read from a file:
f1 = open("configuration.txt")
conf = f1.read() #this string appears to be empty
print f1 returns <open file 'D:\\DIPLOMA\\PLANNER\\Exe\\configuration.txt', mode 'r' at 0x01A080D0>
print f1.read() returns an empty string
I suspect the reason of the failure is that the file is being written immediately before calling getconf.py. If I run main.py when configuration.txt is already there it works. Adding a time delay between the actions doesn't solve the problem.
Would appreciate any help!
I saw other questions related to this:
Python read() function returns empty string
Try to add this line before reading:
file.seek(0)
https://stackoverflow.com/a/16374481/4733992
If this doesn't solve the problem, you can still get the lines one by one and add them to a single string:
file = open("configuration.txt", 'r')
file_data = ""
for line in file:
file_data += line
file.close()
I found my problem, it was due to the fact I didn't close the file that I was writing in. Thanks to all who tried to help.
I would like to write 'yes it does' into a text file I made earlier. when I run my code, it says 'AttributeError: exit'. I was wondering how to remove this error and make it work successfully, thanks for the help.
The code is:
file = ()
def rewrite_test():
open ('testing.txt', 'rb+')
with ('testing.txt'):
print ("yes it does")
rewrite_test()
You can do it like this:
def rewrite_test():
with open('testing.txt', 'w+') as fout:
fout.write('Yes it does.')
Where you had with ('testing.txt'), that would raise an exception because the string 'testing.txt' isn't something that supports the requirements of a with block.
Also you need to open a file for writing not reading, so use 'w' instead of 'r'.
If you don't like using with, you can use the following code:
def rewrite_test() :
f = open('testing.txt', 'w') # You can replace w with a if you want to append
f.write('Yes, it does')
f.close()
rewrite_test()
So it just opens the file, writes to it, and closes it. Also works in Python 2, which doesn't get with. (I am also a Python 2 user, and I don't understand what with does or is.)
If you are simply planning to write to a file using a python script as show below:
#!/usr/bin/python
count = 1
fo = open('DbCount.txt', 'w')
fo.write(str(count))
#fo.flush()
fo.close()
The Dbcount.txt file which was placed in the same folder as the script(attempting to modify the Dbcount.txt). i dont see any change in the txt file and no error is shown by the interpreter, its very strange, any help ?
first of all, always use the with statement variant, that will always close the file, even on errors:
#!/usr/bin/python
count = 1
with open('DbCount.txt', 'w') as fo:
fo.write(str(count))
then the 'w' overwrites your file each time you write to it. If you want to append, use 'a'.
About your specific problem, did you look only in the directory of your script, or in the current directory you're calling the script from? As you wrote your code, the file's path you write to is relative to where you execute your code from.
try:
import os
count = 1
with open(os.path.join(os.path.dirname(__file__), 'DbCount.txt'), 'w') as fo:
fo.write(str(count))
then it should output DbCount.txt in the same path as your script.
I am running a script in python like this from the prompt:
python gp.py /home/cdn/test.in..........
Inside the script i need to take the path of the input file test.in and the script should read and print from the file content. This is the code which was working fine. But the file path is hard coded in script. Now I want to call the path as a command line argument.
Working Script
#!/usr/bin/python
import sys
inputfile='home/cdn/test.in'
f = open (inputfile,"r")
data = f.read()
print data
f.close()
Script Not Working
#!/usr/bin/python
import sys
print "\n".join(sys.argv[1:])
data = argv[1:].read()
print data
f.close()
What change do I need to make in this ?
While Brandon's answer is a useful solution, the reason your code is not working also deserves explanation.
In short, a list of strings is not a file object. In your first script, you open a file and operate on that object (which is a file object.). But writing ['foo','bar'].read() does not make any kind of sense -- lists aren't read()able, nor are strings -- 'foo'.read() is clearly nonsense. It would be similar to just writing inputfile.read() in your first script.
To make things explicit, here is an example of getting all of the content from all of the files specified on the commandline. This does not use fileinput, so you can see exactly what actually happens.
# iterate over the filenames passed on the commandline
for filename in sys.argv[1:]:
# open the file, assigning the file-object to the variable 'f'
with open(filename, 'r') as f:
# print the content of this file.
print f.read()
# Done.
Check out the fileinput module: it interprets command line arguments as filenames and hands you the resulting data in a single step!
http://docs.python.org/2/library/fileinput.html
For example:
import fileinput
for line in fileinput.input():
print line
In the script that isn't working for you, you are simply not opening the file before reading it. So change it to
#!/usr/bin/python
import sys
print "\n".join(sys.argv[1:])
f = open(argv[1:], "r")
data = f.read()
print data
f.close()
Also, f.close() this would error out because f has not been defined. The above changes take care of it though.
BTW, you should use at least 3 chars long variable names according to the coding standards.