How to use a python program stored in a text file? - python

I'm making a troubleshooting program in which I need to take a python program which is stored in a text file, but I can't use the 'import' module. To clarify this, there would be a python program stored as a '.txt' file, and in the main program I would take this text file and be able to use it as a subprogram. I've tried doing this, but I have had no clue of how to go about it, especially since I do not have much experience of Python.
Below is roughly the program. I don't know how to format it either, but here goes:
phonechoice = input("What type of phone do you have?")
if 'iphone' in phonechoice:
#here I would load a text file which contains the program for the iphone
#which asks them what problem they have with their phone and gives a solution
I'm wondering how I can do this. I thought how I could do this and maybe I could 'copy and paste' the program, line by line, into a definition, which I could then use. Would this work, and if it doesn't then in what other way could I do it?

Rename the text file to a python file, i.e. change the extension to ".py". This does not change the fact that it is a text file, just like renaming a picture.jpg file to picture.txt does not change the fact that it's an image file.
If you have some wacky requirement to import a module saved in file with a .txt extension, you can not use an import statement. But it is still possible to import like this:
import imp
my_module = imp.load_source('my_module', 'example.txt')

I am a bit reluctant to answer a "homework" type question, but I will give you some pointers on what you need to do. If I have a text file with this in it:
def main():
print("Hello")
main()
I could execute the code with the exec function like this:
with open("filename.txt") as file: #filename should be the name of the file
data = file.read()
exec(data) #this executes the code
The output would be as expected:
Hello
Hopefully this will shed some light on your problem!

Related

PYTHON How to read txt file from folders on parent directory

I'm new to python, trying to learn and code at the same time, to test what i can do, I learned java, javascript, php, html, css, on my course, so I still remeber the basics.
I reached this problem and after hours i haven't found a solution that I can understand and like.
So this is my structure:
my structure
I want to read the test_input.txt inside the test_input.py, i want that because there are some strings for the user, and i want those strings to change based on the language. I though to write the .txt along side the .py file, but then everytime a function would generate string I would need to make all the language folders again, also if needed to add another language, I also would make various folders on every string occurency.
If possible, i want a solution that read the project inside itself to get the .txt file, because i want this project to be an .exe desktop program. Also, is pyhton good to make simple desktop apps? I'm lookin foward to learn the future languages, like I learned android in java, but I want to use kotlyn because is "better", so I cold make this project in java as a learned and did some in the past, but I want the "what will be most used on the future".
Please correct me in anything if I'm wrong, all this is more about see what I can do, and how, thanks for the help!!!
If I understand you correctly, you want to load and read the txt file in py. If this is the case, like i understood, then perhaps you want to follow this tutorial here:
https://www.pythontutorial.net/python-basics/python-read-text-file/
Also, did you try to open/load it already? If so, did you get an error? Most of the time, it is a path problem for beginners so make sure the path is setup already.
Cheers
I got this script from geeksforgeeks, it got multiple form of how to read a .txt, I am leaving you as well the documentation.
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
https://www.geeksforgeeks.org/reading-writing-text-files-python/

How to read and change BAM files from a Python script?

I'm planning on using a Python script to change different BAM (Binary Alignment Map) file headers. Right now I am just testing the output of one bam file but every time I want to check my output, the stdout is not human readable. How can I see the output of my script? Should I use samtools view bam.file on my script? This is my code.
#!/usr/bin/env python
import os
import subprocess
if __name__=='__main__':
for file in os.listdir(os.getcwd()):
if file == "SRR4209928.bam":
with open("SRR4209928.bam", "r") as input:
content = input.readlines()
for line in content:
print(line)
Since BAM is a binary type of SAM, you will need to write something that knows how to deal with the compressed data before you can extract something meaningful from it. Unfortunately, you can't just open() and readlines() from that type of file.
If you are going to write a module by yourself, you will need to read Sequence Alignment/Map Format Specification.
Fortunately someone already did that and created a Python module: You can go ahead and check pysam out. It will surely make your life easier.
I hope it helps.

Saving data in Python without a text file?

I have a python program that just needs to save one line of text (a path to a specific folder on the computer).
I've got it working to store it in a text file and read from it; however, I'd much prefer a solution where the python file is the only one.
And so, I ask: is there any way to save text in a python program even after its closed, without any new files being created?
EDIT: I'm using py2exe to make the program an .exe file afterwards: maybe the file could be stored in there, and so it's as though there is no text file?
You can save the file name in the Python script and modify it in the script itself, if you like. For example:
import re,sys
savefile = "widget.txt"
x = input("Save file name?:")
lines = list(open(sys.argv[0]))
out = open(sys.argv[0],"w")
for line in lines:
if re.match("^savefile",line):
line = 'savefile = "' + x + '"\n'
out.write(line)
This script reads itself into a list then opens itself again for writing and amends the line in which savefile is set. Each time the script is run, the change to the value of savefile will be persistent.
I wouldn't necessarily recommend this sort of self-modifying code as good practice, but I think this may be what you're looking for.
Seems like what you want to do would better be solved using the Windows Registry - I am assuming that since you mentioned you'll be creating an exe from your script.
This following snippet tries to read a string from the registry and if it doesn't find it (such as when the program is started for the first time) it will create this string. No files, no mess... except that there will be a registry entry lying around. If you remove the software from the computer, you should also remove the key from the registry. Also be sure to change the MyCompany and MyProgram and My String designators to something more meaningful.
See the Python _winreg API for details.
import _winreg as wr
key_location = r'Software\MyCompany\MyProgram'
try:
key = wr.OpenKey(wr.HKEY_CURRENT_USER, key_location, 0, wr.KEY_ALL_ACCESS)
value = wr.QueryValueEx(key, 'My String')
print('Found value:', value)
except:
print('Creating value.')
key = wr.CreateKey(wr.HKEY_CURRENT_USER, key_location)
wr.SetValueEx(key, 'My String', 0, wr.REG_SZ, 'This is what I want to save!')
wr.CloseKey(key)
Note that the _winreg module is called winreg in Python 3.
Why don't you just put it at the beginning of the code. E.g. start your code:
import ... #import statements should always go first
path = 'what you want to save'
And now you have path saved as a string

Python code not writing to file unless run in interpreter

I have written a few lines of code in Python to see if I can make it read a text file, make a list out of it where the lines are lists themselves, and then turn everything back into a string and write it as output on a different file. This may sound silly, but the idea is to shuffle the items once they are listed, and I need to make sure I can do the reading and writing correctly first. This is the code:
import csv,StringIO
datalist = open('tmp/lista.txt', 'r')
leyendo = datalist.read()
separando = csv.reader(StringIO.StringIO(leyendo), delimiter = '\t')
macrolist = list(separando)
almosthere = ('\t'.join(i) for i in macrolist)
justonemore = list(almosthere)
arewedoneyet = '\n'.join(justonemore)
with open('tmp/randolista.txt', 'w') as newdoc:
newdoc.write(arewedoneyet)
newdoc.close()
datalist.close()
This seems to work just fine when I run it line by line on the interpreter, but when I save it as a separate Python script and run it (myscript.py) nothing happens. The output file is not even created. After having a look at similar issues raised here, I have introduced the 'with' parameter (before I opened the output file through output = open()), I have tried flushing as well as closing the file... Nothing seems to work. The standalone script does not seem to do much, but the code can't be too wrong if it works on the interpreter, right?
Thanks in advance!
P.S.: I'm new to Python and fairly new to programming, so I apologise if this is due to a shallow understanding of a basic issue.
Where are the input file and where do you want to save the output file. For this kind of scripts i think that it's better use absolute paths
Use:
open('/tmp/lista.txt', 'r')
instead of:
open('tmp/lista.txt', 'r')
I think that the error can be related to this
It may have something to do with where you start your interpreter.
Try use a absolute path /tmp/randolista.txt instead of relative path tmp/randolista.txt to isolate the problem.

.pyc files and naive encryption

I have a fairly naive thing I want to do and I want to know if someone can answer can tell me if this is just flat out stupid. If what I am going to ask is not stupid but perhaps naive, I'd appreciate if I can get a nudge in a correct direction.
I have a file named pwds.py. Its contents are
import hashlib
class Pwds:
def __init__(self):
pass
def printGood(self,key):
y = hashlib.sha1()
y.update(key.encode('ascii'))
if y.hexdigest() == "db5f60442c78f08eefb0a2efeaa860b071c4cdae":
print("You entered the correct key!")
else:
print("Intruder!")
Then I have another file named runme.py, whose contents are
import pwds
x = input("Please type the password: ")
y = pwds.Pwds()
y.printGood(x)
x = input("Press any key to end")
The first time runme.py is run, a pwds.pyc file is created. My thought was that once the .pyc file was created, I could delete pwds.py and run runme.py as normal. Additionally, I thought the contents of pwds.py would be contained in .pyc but made unreadable since this is a "compiled" Python file. Thus, while I can delete pwds.py and successfully run runme.py, pwds.pyc is pretty much readable if I open it in, say, Notepad.
Thus, the question(s) in general: How can I keep the contents of pwds.py unreadable? What I wanted to do with the above code was to keep "secret" information in a Python file, compile it, and have its contents be accessible only if the correct key were typed. Is this approach too stupid to even consider? I didn't want to get into writing a "garbler" and a "degarbler". I thought this would be a simple and cheap solution.
Thanks for reading this! Please let me know if there is any other information I should provide.
The .pyc file simply contains the compiled python code so it doesn't need to be recompiled everytime you run your program. Thus all strings in it are still readable (you could always look at the binary contents or step through the program via the pdb debugger).
If you want to protect something in your code with a password, you have to encrypt it with strong encryption and only store the encrypted version. The users's key/password is then used to decrypt the data.

Categories

Resources