My Python program requests some user input:
n = int(input())
for i in range(n):
s = input()
# ...
For debugging purposes, I would like to create a test input.txt file like this:
3
string1
string2
string3
so that I need not to manually enter data from the keyboard every time I launch it for debug.
Is there any way to get input() from text file, not from keyboard (without changing program code).
I am using Wing Personal as a dev tool.
Update
I know for sure, that there exist bots which are able to test python programs passing various inputs and comparing output with known answers. I guess these bots do not hit the keyboard with iron fingers. Maybe they use command-line tools to pass input.txt to the Python so that it reads input() from that file, not from keyboard. I would like to learn how to do it.
Input reads from Standard input so if you use bash you can redirect stdin to a file
without changing your code
in bash you would run something like
cat textfile | programm.py
or
< textfile programm.py
I've noticed that none of these solutions redirects the stdin from Python. To do that, you can use this snippet:
import sys
sys.stdin = open('input.txt', 'r')
Hopefully, that helps you!
You can read the file into a list like this:
with open('filename.txt', 'r') as file:
input_lines = [line.strip() for line in file]
s would be data in index i.
n = int(input())
for i in range(n):
s = input_lines[i]
# ...
Make sure your py file is in the same dir as your txt file.
You can create a test.py file which is used to run your test. In the test.py, you will read the content of input.txt and import the programming.
For example, in test.py file.
import main_code
with open('input.txt', 'r') as file:
lines = file.readlines()
for line in lines:
s = line
"""
working with the input.
"""
Related
I'm new to PyMOL, and I'm trying to write a python script that will generate a .txt file and save a PyMOL command output to it. Let's say it has an array containing names of pdb files and a for loop that aligns each one to some specific protein:
pdb = ["191L", "192L", "193L", "194L"]
cmd.fetch("190L")
for i in pdb:
cmd.fetch(i)
cmd.align(i, "190L")
PyMOL will calculate the RMSD for each alignment. How can I write my script so that it will take each RMSD and save it to a text file?
Here's what I have so far:
def get_rmsd():
cmd.fetch("190L")
for i in pdb:
cmd.fetch(i)
output = open("rmsd.txt", "w")
data = cmd.align(i, "190L")
data = str(data)
output.write(data)
stored.f.close()
When I call the function on PyMOL, it fetches and aligns the file like it's supposed to, but no text file is created.
Figured out the answer to my own question, the solution was embarrassingly easy lol.
Assign variables to each desired output, e.g.:
output = cmd.align("190L", "191L")
Run the script in PyMOL as is, then feed the python code into it line by line, beginning with "python" and closing with "python end." In my case, something like:
python
with open("rmsd.txt", "w") as f:
f.write(output)
f.close()
python end
A really basic example but that's the gist of it.
I wouldn't use the pymol.Scratch_Storage class. I would keep it simple and do something like:
Create a new file "test.py"
Copy the following:
from pymol import cmd
import os
def get_rmsd(pdbs, align_to):
# a bit more reusable
cmd.fetch(align_to)
with open("rmsd.txt", "w") as w:
# using context management will close the rmsd.txt automatically
for pdb in pdbs:
cmd.fetch(pdb)
line = cmd.align(pdb, align_to)
w.write(f"{line}\n")
print(f"outfile: {os.path.join(os.getcwd(), 'rmsd.txt')}")
get_rmsd(["191L", "192L", "193L", "194L"], "190l")
Run script from PyMOL terminal with: run test.py
for i in pdb:
cmd.fetch(i)
output = open("rmsd.txt", "w")
data = cmd.align(i, "190L")
data = str(data)
output.write(data)
stored.f.close()
try:
for i in pdb:
cmd.fetch(i)
output = open("rmsd.txt", "a")
data = cmd.align(i, "190L")
output.write("%s\n" % data)
output.close()
should do the job
I am writing a script where I first read a file using
with open('file', 'r') as file,
do some operation, and then write it to a new file using
with open('newfile', 'w') as newfile.
My question is, what do I need to change in the script to make it general for a number of files, so that I can just call the script with the file name from the terminal like python3 script.py file.ext? Also, is there a way to write the output back into the original file using this method?
One way of doing this is:
import sys
file=open(sys.argv[1], "r")
newfile=open("example.txt", "w")
content=file.read()
#do stuff to content here such as content=content.upper()
newfile.write(content)
If you inputted into the command line:
python script.py aaaaaa.txt
Then the file you set as the output would have the edited content of aaaaaa.txt
Hope this helps :)
I get how to open files, and then use Python's pre built in functions with them. But how does sys.stdin work?
for something in sys.stdin:
some stuff here
lines = sys.stdin.readlines()
What's the difference between the above two different uses on sys.stdin? Where is it reading the information from? Is it via keyboard, or do we still have to provide a file?
So you have used Python's "pre built in functions", presumably like this:
file_object = open('filename')
for something in file_object:
some stuff here
This reads the file by invoking an iterator on the file object which happens to return the next line from the file.
You could instead use:
file_object = open('filename')
lines = file_object.readlines()
which reads the lines from the current file position into a list.
Now, sys.stdin is just another file object, which happens to be opened by Python before your program starts. What you do with that file object is up to you, but it is not really any different to any other file object, its just that you don't need an open.
for something in sys.stdin:
some stuff here
will iterate through standard input until end-of-file is reached. And so will this:
lines = sys.stdin.readlines()
Your first question is really about different ways of using a file object.
Second, where is it reading from? It is reading from file descriptor 0 (zero). On Windows it is file handle 0 (zero). File descriptor/handle 0 is connected to the console or tty by default, so in effect it is reading from the keyboard. However it can be redirected, often by a shell (like bash or cmd.exe) using syntax like this:
myprog.py < input_file.txt
That alters file descriptor zero to read a file instead of the keyboard. On UNIX or Linux this uses the underlying call dup2(). Read your shell documentation for more information about redirection (or maybe man dup2 if you are brave).
It is reading from the standard input - and it should be provided by the keyboard in the form of stream data.
It is not required to provide a file, however you can use redirection to use a file as standard input.
In Python, the readlines() method reads the entire stream, and then splits it up at the newline character and creates a list of each line.
lines = sys.stdin.readlines()
The above creates a list called lines, where each element will be a line (as determined by the end of line character).
You can read more about this at the input and output section of the Python tutorial.
If you want to prompt the user for input, use the input() method (in Python 2, use raw_input()):
user_input = input('Please enter something: ')
print('You entered: {}'.format(user_input))
To get a grasp how sys.stdin works do following:
create a simple python script, let's name it "readStdin.py":
import sys
lines = sys.stdin.readlines()
print (lines)
Now open console any type in:
echo "line1 line2 line3" | python readStdin.py
The script outputs:
['"line1 line2 line3" \n']
So, the script has read the input into list (named 'lines'), including the new line character produced by 'echo'. That is.
According to me sys.stdin.read() method accepts a line as the input from the user until a special character like Enter Key and followed by Ctrl + D and then stores the input as the string.
Control + D works as the stop signal.
Example:
import sys
input = sys.stdin.read()
print(input)
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
After running the program enter two numbers delimited by space and after finishing press Control + D once or twice and you will be presented by the sum of the two inputs.
for something in sys.stdin:
some stuff here
The code above does not work as you expect because sys.stdin is a file handle - it is a file handle to the stdin. It will not reach the some stuff here line
lines = sys.stdin.readlines()
When the script above is run in an interactive shell, it will block the execution until a user presses Ctrl-D, which indicates the end of the input.
It will read the source file line by line. It is widely used in Online Judge System.
For example: suppose we have only one number 2 will be used in the file.
import sys
if __name__ == "__main__":
n = int(sys.stdin.readline().strip())
Read the file line by line means read the number 2 (only one line in this case). Using the strip to remove unneeded space or other specified characters. This will result in n = (integer) 2.
If we have a file with two lines like:
1
2
Then, sys.stdin.readline().strip() will transform it to one line (a list, named n) with two elements 1, 2. Then we cannot use int transformer now but we can use int(n[0]) and int(n[1]) instead.
I have a python script which uses a text file and manipulate the data from the file and output to another file. Basically I want it to work for any text file input. Right now I readline from the file and then print the output to screen. I want the output in a file.
So user can type the following and test for any file:
cat input_file.txt | python script.py > output_file.txt.
How can I implement this in my script? Thank You.
cat is command in linux. I don't know how it works.
The best way to do this is probably to call the input and output files as arguments for the python script:
import sys
inFile = sys.argv[1]
outFile = sys.argv[2]
Then you can read in all your data, do your manipulations, and write out the results:
with open(inFile,'r') as i:
lines = i.readlines()
processedLines = manipulateData(lines)
with open(outFile,'w') as o:
for line in processedLines:
o.write(line)
You can call this program by running python script.py input_file.txt output_file.txt
If you absolutely must pipe the data to python (which is really not recommended), use sys.stdin.readlines()
This method (your question) describes reading data from STDIN:
cat input_file.txt | python script.py
Solution: script.py:
import sys
for line in sys.stdin:
print line
The method in above solutions describes taking argument parameters with your python call:
python script.py input_file.txt
Solution: script.py:
import sys
with open(sys.argv[1], 'r') as file:
for line in file:
print line
Hope this helps!
cat input_file.txt | python script.py > output_file.txt.
You can passing a big string that has all the data inside input_file.txt instead of an actual file so in order to implement your python script, just take that it as a string argument and split the strings by new line characters, for example you can use "\n" as a delimiter to split that big string and to write to an outputfile, just do it in the normal way
i.e. open file, write to the file and close file
Sending output to a file is very similar to taking input from a file.
You open a file for writing the same way you do for reading, except with a 'w' mode instead of an 'r' mode.
You write to a file by calling write on it the same way you read by calling read or readline.
This is all explained in the Reading and Writing Files section of the tutorial.
So, if your existing code looks like this:
with open('input.txt', 'r') as f:
while True:
line = f.readline()
if not line:
break
print(line)
You just need to do this:
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
while True:
line = fin.readline()
if not line:
break
fout.write(line)
If you're looking to allow the user to pass the filenames on the command line, use sys.argv to get the filenames, or use argparse for more complicated command-line argument parsing.
For example, you can change the first line to this:
import sys
with open(sys.argv[1], 'r') as fin, open(sys.argv[2], 'w') as fout:
Now, you can run the program like this:
python script.py input_file.txt outputfile.txt
cat input_file.txt | python script.py > output_file.txt
Basically, python script needs to read the input file and write to the standard output.
import sys
with open('input_file.txt', 'r') as f:
while True:
line = f.readline()
if not line:
break
sys.stdout.write(line)
I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.
I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:
from sys import argv
script, filename = argv
print "Who are you?"
name = raw_input()
print "What file are you looking for today?"
file = raw_input()
print (file)
print "Ok then, here's the file you wanted."
print "Would you like to delete the contents? Yes or No?"
I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip() remove notations like this: /n
print ''.join(file('example.txt'))
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
single line to read/print contents of a file
reading file : example.txt
print(open('example.txt', 'r').read())
output:
u r reading the contents of example.txt file
Reading and printing the content of a text file (.txt) in Python3
Consider this as the content of text file with the name world.txt:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read() like this:
content_of_file= file.read()
Finally we will just print the content_of_file variable using print command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!