How can I tell python to edit another python file? - python

Right now, I have file.py and it prints the word "Hello" into text.txt.
f = open("text.txt")
f.write("Hello")
f.close()
I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:
f = open("list.py")
f.write("a = 1")
f.close
When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?

If you want to append a new line to the end of a file
with open("file.py", "a") as f:
f.write("\na = 1")
If you want to write a line to the beginning of a file try creating a new one
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))

with open("list.py","a") as f:
f.write("a=1")
This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.
Example:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.py
a=1
print(a+1)
Output from list.py:
>>>
2
>>>
As you see, there is a variable in list.py called a equal to 1.

I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:
for reading:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
for writing:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
For more information, please, read documentation.

Related

How to open and print the contents of a file line by line using subprocess?

I am trying to write a python script which SSHes into a specific address and dumps a text file. I am currently having some issues. Right now, I am doing this:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it. However, this really messes up the format when I print "need". Is there any way to simply use subprocess and read the file line by line? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated :)
You don't need to use the subprocess module to print the entire file line by line. You can use pure python.
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)

Python seemingly not reading from text file

files = []
with open("[...].log", "a+") as posshell:
for line in files:
print(line)
posshell_files.append(line)
I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.
You are passing the incorrect second argument to the open call to read the file in this way:
posshell_files = []
with open("posshell.log", "r") as posshell:
for line in posshell:
print(line)
posshell_files.append(line)
According to the Python docs for open, 'r' if the default flag for reading while 'a+' is for reading and writing but you will have to do so in a different manner:
with open("posshell.log","a+") as f:
f.seek(0)
print(f.read())
Try this
with open('posshell.log') as p:
content = p.readlines()
content = [x.strip() for x in content]

How can i save this into a variable so that i can save it to a file

I have a bit of code which prints what I want to save but I cant save it as a variable because of the format. Please can you show me how to save this as a variable so that I can save it into a file
It wont let me add a picture but this is what I want to add to a variable (What its printing)
print(text[i],end="")
x = text[i]
with open("output.txt", 'w') as f:
f.write(x)
or
with open("output.txt", 'w') as f:
f.write(text[i])
Open a file:
f = open('filename','w')
Write a line of text to the file:
f.write(text[i])
And finally close the file:
f.close()

Python: Writing to a File

I've been having trouble with this for a while. How do I open a file in python and continue writing to it but not overwriting what I had written before?
For instance:
The code below will write 'output is OK'.
Then the next few lines will overwrite it and it will just be 'DONE'
But I want both
'output is OK'
'DONE'
in the file
f = open('out.log', 'w+')
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
f.close()
# some other work
f = open('out.log', 'w+')
f.write('done\n')
f.flush()
f.close()
I want to be able to freely open and write to it in intervals. Close it. Then repeat the process over and over.
Thanks for any help :D
Open the file in append mode. It will be created if it does not exist and it will be opened at its end for further writing if it does exist:
with open('out.log', 'a') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
# some other work
with open('out.log', 'a') as f:
f.write('done\n')
Just pass 'a' as argument when you open the file to append content in it. See the doc
f = open('out.log', 'a')
You need to open the file in append mode the second time:
f = open('out.log', 'a')
because every time you open the file in the write mode, the contents of the file get wiped out.
After the first writting, you need to use f = open('out.log', 'a') to append the text to the content of your file.
with open("test.txt", "a") as myfile:
myfile.write("appended text")

Python command isn't reading a .txt file

Trying to follow the guide here, but it's not working as expected. I'm sure I'm missing something.
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
file = open("C:/Test.txt", "r");
print file
file.read()
file.read()
file.read()
file.read()
file.read()
file.read()
Using the readline() method gives the same results.
file.readline()
The output I get is:
<open file 'C:/Test.txt', mode 'r' at 0x012A5A18>
Any suggestions on what might be wrong?
Nothing's wrong there. file is an object, which you are printing.
Try this:
file = open('C:/Test.txt', 'r')
for line in file.readlines(): print line,
print file invokes the file object's __repr__() function, which in this case is defined to return just what is printed. To print the file's contents, you must read() the contents into a variable (or pass it directly to print). Also, file is a built-in type in Python, and by using file as a variable name, you shadow the built-in, which is almost certainly not what you want. What you want is this:
infile = open('C:/test.txt', 'r')
print infile.read()
infile.close()
Or
infile = open('C:/test.txt', 'r')
file_contents = infile.read()
print file_contents
infile.close()
print file.read()
You have to read the file first!
file = open("C:/Test.txt", "r")
foo = file.read()
print(foo)
You can write also:
file = open("C:/Test.txt", "r").read()
print(file)

Categories

Resources