PYTHON How to read txt file from folders on parent directory - python

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/

Related

Using os.system to operate a .py file on many files

I hope that I can ask this in a clear way, im very much a beginner to python and forums in general so I apologise if i've got anything wrong from the start!
My issue is that I am currently trying to use os.system() to enable a program to run on every file within a directory (this is a directory of ASCII tables which I am crossing with a series of other tables to find matches.
import os
for filename in os.listdir('.'):
os.system('stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits'%(filename,filename))
So what im hoping this would do is for every 'filename' it would operate this program known as stilts. Im guessing this gets interrupted/doesn't work because of the presence of apostrophes ' in the line of code itself, which must disrupt the syntax? (please correct me if I am wrong)
I then replaced the ' in os.system() with "" instead. This, however, stops me using the %s notation to refer to filenames throughout the code (at least I am pretty sure anyway).
import os
for filename in os.listdir('.'):
os.system("stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits"%(filename,filename))
This now runs but obviously doesn't work, as it inteferes with the %s input.
Any ideas how I can go about fixing this? are there any alternative ways to refer to all of the other files given by 'filename' without using %s?
Thanks in advance and again, sorry for my inexperience with both coding and using this forum!
I am not familiar with os.system() but maybe if you try do some changes about the string you are sending to that method before it could behave differently.
You must know that in python you can "sum" strings so you can save your commands in a variable and add the filenames as in:
os.system(commands+filename+othercommands+filename)
other problem that could be working is that when using:
for file in os.listdir()
you may be recievin file types instead of the strings of their names. Try using a method such as filename.name to check if this is a different type of thing.
Sorry I cant test my answers for you but the computer I am using is too slow for me to try downloading python.

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

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!

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.

Finding and adding to a .kml file using python

I am not a very good coder. But I really want to automate something I have to do at work. Basically, I have a bunch of placemarkers in google earth showing hand-holes of a municipal fiber network. I have a few pictures of each hand-hole that I want to place as a tag in the .kml file. Basically, I want to have it so when they click on a placemarker in google earth, it brings up the little description bubble and shows the pictures for each hand-hole and probably some other vital info.
Right now I have each hand hole labeled as either TO-. So hand-hole number 101 has a TO-101. And I have already made a script that has renamed all the pictures to match the name. So, if hand hole TO-101 has 3 pictures, they would be TO-101-1.jpg, TO-101-2.jpg, TO-101-3.jpg.
So, basically, I am trying to make a python script that reads the kml file (which I have done succesfully). I need it to find the corresponding TO-101 or whichever handhole in the .kml file, add a line below that line that reads:
<description> <img src="TO-101-1.jpg"><img src="TO-101-2.jpg"></description>.
Need to do this for about 5000 pictures and 2000 or so hand-holes.
I have tried to this:
import string, glob, sys, os, fileinput
f = open('./hand-holes.kml','r')
while f:
line = f.readline()
if line == "<name>TO-101</name>":
print line
And I can't even get it to find and print that line. I know the line is in the file, and I know the path is right. Because if I comment out the if line == "TO-101" it displays the contents of the file. So, if I can't even get that to work, there is no chance I am going to get the rest of it to work. I have tried looking at several pieces of search and replace type python example code. Some of it uses a string library, which I am not sure if I need to use.
Can anyone help me? Thanks
Renosis
I'm assuming the reason your if line == "<name>TO-101</name>" line doesn't work is because it probably has whitespace preceding it. If you changed it to line.strip() == ... then it would presumably work.
Your best bet would be to implement an XML handler to read in the existing file, parse it, and add the new section. Start maybe with xml.sax

.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