How can I run a text file use Python?
For example; if the text file is called textfile.txt, and it contains the line:
print("Hello")
How can I use Python to run this as lines of code?
You can use exec: https://docs.python.org/3/library/functions.html#exec
so your code would look somehow like this:
filehandle = open("filename.txt","r")
code_to_execute = filehandle.read()
exec(code_to_execute)
remeber that your file has to have correct syntax so no syntax error occours (mostly its about indentation)
Simply call the python interpreter and pass it the file as such:
python yourfile.txt
Related
I am creating a simple python file in unix, just to open and write some test in it, but getting error while execution. Using Python 2.4.3
file = open(“testfile.txt”, “w”)
file.write(“This is a test”)
file.write(“To add more lines.”)
file.close()
Error:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `file = open(“testfile.txt”, “w”)'
I believe you are using curly quotes “” (e.g. from Microsoft Word, etc..) rather than actual single and double quote chars '' "".
Make sure you are using a regular text editor, not a rich text editor. That's the problem.
The problem is that “ is not a valid quote in Python. Try copying and pasting this code into your file/terminal and you should then realise the difference.
file = open("testfile.txt", "w")
file.write("This is a test")
file.write("To add more lines.")
file.close()
In addition to the "smart" quotes that need to be plain ASCII " characters you need a "shebang" line as the first line of the script. Otherwise it is likely to be treated as a shell script and handed to /bin/sh for execution. You should insert this as the first line of the file:
#!/usr/bin/env python
Or run it via python ./x.py.
I think quotes are the problem.
can you try a content manager
with open('testfile.txt', 'w') as output_file:
output_file.write("Your Text Here")
use of context managers is to properly manage resources. In fact, that's the reason we use a context manager . The act of opening a file consumes a resource (called a file descriptor), and this resource is limited by your OS. Similarly writing.
That is to say, there are a maximum number of files a process can have open at one time.
I have file loadMe.txt that i want to use in my script main.py. To do so I execute script from command line by command:
python main.py < loadMe.txt
How can I access to this loadMe.txt in my script in this "<" way? Also how operator "<" is named?
< is called "input redirection". It uses the file as an input source. You can think of cmd < file as equivalent to cat file | cmd.
In Python, there are a variety of ways to read from it. A basic input() command will read until a new line. You can also do something like this:
import sys
# use `sys.stdin` like the file.
whole_contents = sys.stdin.read()
# Or something like
first_five_chars = sys.stdin.read(5)
I have a python file that isn't working.
I would like to run this script on it:
with open('beak', 'rb+') as f:
content = f.read()
f.seek(0)
f.write(content.replace(b'\r', b''))
f.truncate()
Source
I don't know how to make multiple lines on command line and I am not really sure how to execute my code. Do I just put my file name in place of 'beak' and do I just cd to the folder my file is in before I execute this script?
You can type that into the Python command line. Type the first line and return, it will recognize that you're in the middle of a with clause and allow you to type the remaining lines one at a time (be sure to get the indentation right). After the last line, return twice and it will execute.
This script assumes that you are going to read a file named "beak". You need to run this script from the same directory where "beak" is. ("beak" should really have an extension, like ".txt", depending on what kind of file it is).
Doing long scripts from the command line like this is not the best way -- it's better to put this code in a file ("reader.py", for example -- and put reader.py in the same directory as "beak"). Then you can simply execute by typing "python reader.py".
I would like to know if it's possible to check if a Python code has a correct syntax, without running it, and from a Python program. The source code could be in a file or better in a variable.
The application is the following: I have a simple text editor, embedded in my application, used for editing Python scripts. And I'd like to add warnings when the syntax is not correct.
My current idea would be to try importing the file and catch a SyntaxError exception that would contains the erroneous line. But I don't want it to execute at all. Any idea?
That's the job for ast.parse:
>>> import ast
>>> ast.parse('print 1') # does not execute
<_ast.Module at 0x222af10>
>>> ast.parse('garbage(')
File "<unknown>", line 1
garbage(
^
SyntaxError: unexpected EOF while parsing
I just found out that I could probably use the compile function. But I'm open to better suggestions.
import sys
# filename is the path of my source.
source = open(filename, 'r').read() + '\n'
try:
compile(source, filename, 'exec')
except SyntaxError as e:
# do stuff.
You could use PyLint and call it when the file is saved, and it'll check that file for errors (it can detect much more than just syntax errors, look at the documentation).
I have a text file inside which I have paths to a few python files and the arguments that I would specify when I run them in a command prompt.
I am looking for a python script that opens up the text file and runs the python programs specified in the text file along with the provided arguments.
The text file will look something like
`C:\hello.py world
C:\square.py 5`
i think you should refer to below :
Calling an external command in Python
Step One
read all lines in your command file get a list of python script file name and arguments
like: " C:\hello.py and argument: word "
Step Two
call them in below code style
from subprocess import call
call(["python C:\hello.py", "word"])
......
I don't think this post deserves down voting. But from now on I would suggest to OP to look for a solution yourself, and then if you can't find the answer post on stack overflow!
from subprocess import call
with open("somefile.txt", 'r') as f:
some_files_to_run = [line.split('\n')[0] for line in f.readlines()]
for file_to_run in some_files_to_run:
call(["python", file_to_run])