I'm trying to set up a program to be able to read in text located the the program file but which is not assigned to a variable.
What I mean by that is:
There once was a boy who went on an adventure.
He did many, many thing. Yada, yada, yada.
[begin code here to read text]
I'm trying to design it to take in the typed lines of text and then be able to give variable names to each line until it reaches a stopping point like a blank like or a line with only a period. Assuming the text will begin on line 2.
If anybody has any ideas on how to make this work they would be very much appreciated.
Maybe if you tried smuggling the text in as a docstring?
"""Test Doc String"""
print __doc__
Results in (if this code is saved in source.py):
me#Bob:~$ python source.py
Test Doc String
This relies upon keeping your program within a single file. If you import that file (e.g. from source.py to target.py) you would then have to refer to that docstring using the name of the source file (e.g. source.doc). Anyway, you can assign doc to the variable of your choice and then parse away...
But do you really want to do this? Why not read the text in from a separate text file?
Related
This seems like a pretty obvious/dumb question, but there are a few specifications that make this a bit harder.
Let's say I have a program that takes 3 numbers from a user and does mathematical processes to them to get outputs. Then I open("file", "r") to write those variables to a file.
Then, let's say another program then imports them and uses them for other processes. I need to be able to import that file as Python code. To be clear: I am not saving text, I am saving python code to a file that is not a .py file.
Is there any way to save and import Python code to and from a non-.py file? And how?
EDIT: In the file I'm saving and importing, I'm also saving Python functions. I cannot simply save the variables themselves; I need the variable names, values, and python functions to be saved as normal text in a file, but when I import the file, it should be parsed as Python code.
Probably not a good idea to store computation result as code & then import it from elsewhere. You should use a proper data format to store the results - and import it as data. Use JSON or pickle etc.
However, if you do want to shoot yourself in the foot, Python gives you the tools to do that:
Let's say i have some code in a file temp.txt
number3=30
def f():
return 'method'
Then you can do this:
with open('temp.txt') as f:
code = f.read()
exec(code)
print(number3)
print(f())
Which outputs:
30
method
If i got this right, this might be done via eval function e.g. you save all code to be executed into a string and then save into a file.
When you need that executed read the file, tke the string and eval it
I must say however that using eval is a bad (very bad) practice and i would advice against it unless there is no other solution that you can find
Let me preface by saying I am very new to programming. I'm creating a fun program that I can use to start my day at work. One of the things I want it to do is display a random compliment. I made a text file that has multiple lines in it. How do I store that text file then open it?
I've opened text files before that were on my desktop but I want this one to be embedded in the code so when I compile the program I can take it to any computer.
I've googled a ton of different key words and keep finding the basics of opening and reading txt files but that's not exactly what I need.
Perhaps start with defining a default path to your file; this makes it easier to change the path when moving to another computer. Next, define a function in your program to read and return the contents of the file:
FILE_PATH = "my/path/to/file/"
def read_file(file_name):
with open(FILE_PATH + file_name) as f:
return f.read()
With that in place, you can use this function to read, modify, or display the file contents, for example to edit something from your file:
def edit_comments():
text = read_file("daily_comments.txt")
text = text.replace("foo", "foo2")
return text
There are obviously many ways to approach this task, this is just a simple example to get you started.
html is just text, often very repetitive. I have a simple homework webpage. I'm trying to automate the webpage production.
I have Python routines for producing html (I made them, so they are primitive, but they all work):
makeCheckboxes.py
makeDropdownboxes.py
makehtmlTable.py
makeRadiobuttons.py
makeTextboxes.py
makeThankyouPHP.py
and lastly:
makeWebpage.py
They all just output a text file.
Rather than lump all these in one very big, long file (I lose the plot easily), I'd like to call the one or ones I want from makeWebpage.py and run it, then knot the sections together into 1 text file.
They are all in /home/pedro/textTohtml/ I run them in a bash terminal.
I don't need all the routines each week.
All I need to know is, how many sections I want and what's in it.
For example, let's say next week: Section 1 is radio buttons, Section 2 is Textboxes (fill in the gaps exercise)
Can I call the 2 routines from makeWebpage.py without actually defining them within as functions?
The functions themselves produce a text file which I can then open and integrate into the webpage template.
EDIT: Thanks for the answers. What I need is to import the whole file, each of which will then have its own inner functions.
If I do this:
import file as fl
Will it then run fl?
Or is it better to run subprocess?
How does this help you:
Call a function from another file in Python
You just need to use
from file import function
To import the functions at the start of your makeWebpage.py file. Then makeWebpage.py can call any of the functions any time it wants.
If you only need a function:
from FILE import FUNCTION
FUNCTION(*args,**kwargs)
If you want to run/execute the python file (everything):
import os
os.system("FILE")
[NOTE] The file must be a string and contain the extension, eg "some_file.py" whereas in import statements only the file name is specified in plaintext.
In both cases both files must be in the same directory unless a path is specified ("c:\Users\MyProfile\PythonFiles\python.py" or "/Users/MyProfile/PythonFiles\python.py")
EDIT: If you are importing an entire file (STRICTLY LIKE THIS!) from FILE import * you can name variables or functions with an underscore before it to prevent it from being imported (more info on PEP 8 https://www.python.org/dev/peps/pep-0008/#id36)
I was asked to write a program to find string "error" from a file and print matched lines in python.
Will first open a file with read more
i use fh.readlines and store it in a variable
After this, will use for loop and iterate line by line. check for the string "error".print those lines if found.
I was asked to use pointers in python since assigning file content to a variable consumes time when logfile contains huge output.
I did research on python pointers. But not found anything useful.
Could anyone help me out writing the above code using pointers instead of storing the whole content in a variable.
There are no pointers in python, although something like pointer can be implemented, but is not worth the efforts for your case.
As pointed out in the solution of this link,
Read large text files in Python, line by line without loading it in to memory .
You can use something like:
with open("log.txt") as infile:
for line in infile:
if "error" in line:
print(line.strip()) .
The context managers will close the file automatically and it only reads one line at a time. When the next line is read, the previous one will be garbage collected unless you have stored a reference to it somewhere else.
You can use a dictionary by using key-pair value. Just dump the log file into dictionary wherein the key would be words and value would be the line number. So if you search for string "error" you will get the line numbers they are present it and accordingly you can print them. Since searching in dictionary or hashtable is in constant time O(1) it will take less time. But yes storing might take time depends if you avoid collision.
I used below code instead of putting the data in a variable and then for loop.
for line in open('c182573.log','r').readlines():
if ('Executing' in line):
print line
So there is no way that we can implement pointers or reference in python.
Thanks all
There are no pointers in python.
But something like pointer can be implemented, but for your case it's not required.
Try Below Code
with open('test.txt') as f:
content = f.readlines()
for i in content:
if "error" in i:
print(i.strip())
Even if you want to understand Python variables as pointers go to this link
http://scottlobdell.me/2013/08/understanding-python-variables-as-pointers/
I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target .doc file is not the only one but can be many of them. All the target .doc files are always in the same folder (same path) but all of them don't have the same name. The .doc file FROM where I want to move entire text is only one, always in the same folder (same path) and always with the same file name.
Names of the target are only similar but as I have said before, not the same. Here is the point of whole script:
Target .doc files have the names:
HD1.doc HD2.doc HD3.doc HD4.doc
and so on
What I would like to have is moved the entire (but really all of the text, must be 100% all) text into the .doc file with the highest ( ! ) number. The target .doc files will always start with ''HD'' and always be similar to above examples.
It is possible that the doc file (target file) is only one, so only HD1.doc. Therefore ''1'' is the maximum number and the text is moved into this file.
Sometimes the target file is empty but usually won't be. If it won't be then the text should be moved to the end of the text, into first new line (no empty lines inbetween).
So for example in the target file which has the maximum number in its name is the following text:
a
b
c
In the file from which I want to move the text is:
d
This means I need in the target file this:
a
b
c
d
But no empty lines anywhere.
I have found (showing three different codes):
http://paste.pocoo.org/show/169309/
But neither of them make any sense to me. I know I would need to begin with finding the correct target file (correct HDX file where X is the highest number - again all HD files are and will be in the same folder) but no idea how to do this.
I meant microsoft office word .doc files. They have "pure text". What I mean with pure text is that Im also able to see them in notepad (.txt). But I need to work with .doc extensions. Python is because I need this as automated system, so I wouldn't even need to open any file. Why exsactly python and not any other programming language? The reason for this is because recently I have started learning python and need this script for my work - Python is the "only" programming language that Im interested for and thats why I would like to make this script with it. By "really 100%" I meant that entire text (everything in source file - every single line, no matter if there are 2 or several thousands) would be moved to correct (which one is correct is described in my first post) target file. I cannot move the whole file because I need to move entire text (everything gathered - source file will be always the same but contest of text will be always different - different words in lines) and not whole file because I need the text in correct .doc file with correct name and together (with "together" i mean inside the same file) with already exsisting text IF is there anything already in the target file. Because its possible that the correct target file is empty also.
If someone could suggest me anything, I would really appreciate it.
Thank you, best wishes.
I have tried to ask on openoffice forum but they don't answer. Seen the code could be something like this:
from time import sleep
import win32com.client
from win32com.client import Dispatch
wordApp = win32com.client.Dispatch('Word.Application')
wordApp.Visible=False
wordApp.Documents.Open('C:\\test.doc')
sleep(5)
HD1 = wordApp.Documents.Open('C:\\test.doc') #HD1 word document as object.
HD1.Content.Select.Copy() #Selects entire document and copies it. `
But I have no idea what does that mean. Also I cannot use the .doc file like that because I never know what is the correct filename (HDX.doc where X is maximum integer number, all HD are in same directory path) of the file and therefore I cannot use its name - the script should find the correct file. Also ''filename'' = wordApp.Documents.open... would for sure give me syntax error. :-(
Openoffice ships with full python scripting support, have a look: http://wiki.services.openoffice.org/wiki/Python
Might be easier than trying to mess around with MS Word and COM apis.
So you want to take the text from a doc file, and append it to the end of the text in another doc file. And the problem here is that's MS Word files. It's a proprietary format, and as far as I know there is not module to access them from Python.
But if you are on Windows, you can access them via the COM API, but that's pretty complicated. But look into that. Otehrwise I recommend you to not us MS Word files. The above sounds like some sort of logging facility, and it sounds like a bad idea to use Word files for this, it's too fragile.