Reputation: 73
I am working on a programming assignment, and the directions specify:
"Your program should terminate when it reaches the end of the input file, or the end-of-file on stdin (when control-D is typed from the keyboard under Linux)."
This is what I have so far:
userInput = rawInput()
while userInput != "":
#other stuff the program will do
This is my first time programming in python, and I am using pycharm editor. I am a little confused if this works. Normally in java I would check if userInput is null, but it seems like python doesnt have null objects? Also, does this account for the part in the instructions that says "when control-D is typed from the keyboard under Linux)."?
Since I'm using pyCharm to edit and run my file before turning it in, how do I test to simulate when control-D is typed from the keyboard under Linux" ?
Upvotes: 0
Views: 858
Reputation: 72
first terminating the program when it reaches end of file.
open the file using open()
fp=open("sample.txt","r")
read the lines using for loop
for l in fp:
fp=open("sample.txt","r")
for l in fp:
print (l,end='')
if you are working with python2.7
fp=open("sample.txt","r")
for l in fp:
print l
Now we can use exception handling to terminate the input when crtl+D is pressed in stdin.here i am specifying the sample program
try:
str1=raw_input("Enter the String :")
print "Given String :",str1
except:
print "User typed ctrl+d"
Upvotes: -1
Reputation: 11
For performing operations till EOF
, see my example code below. The outer for
loop iterates till the last line, or you can say, the End-Of-File.
infile = open('input.txt','r')
lines = infile.readlines()
whitespace_count=0
for data in lines:
#do your stuff here, for example here i'm counting whitespaces in input file
for character in data:
if character.isspace():
whitespace_count +=1
print whitespace_count
And, when you need to do your work directly from STDIN, consider the following code below, here sys.stdin
acts just like reading an input file. After you have entered enough input, tap CTRL+D till program exits
import sys
for line in sys.stdin:
for data in line:
for character in data:
if character.isspace():
whitespace_count +=1
print whitespace_count
Upvotes: 0