Chapter 18 Input/Output
18.1 Setting up an IDE
Programs in this section cannot be run in the sandbox. You need to use the server account.
Server account Anaconda Python installation with the Spyder IDE Jypyter notebooks
Programs in this section cannot be run in the sandbox. You need to use the server account.
18.1.1 Code
x=input()
print(x)
x=input("give me a number: ")
print(x)
18.2 Function - readline()
f=open("file.txt")
line=f.readline()
print(line)
print(line[0])
18.3 Function - rstrip()
Every line read from a file has a newline character at the end. You replace it using rstrip()
.
f=open("file.txt")
line=f.readline()
line=line.rstrip('\n')
18.4 Function - readlines()
f=open("file.txt")
lines=f.readlines()
print(lines)
print(lines[0])
print(lines[0][0])
Here lines
is a list of strings. Therefore, if you want to remove newline characters, you need to use a loop and run rstrip()
for every member of the list.
18.5 Reading from a file
So far we supplied all data to our codes written in the sandbox. This gets annoying, if the browser crashes for some reason and you need to start from scratch by copying the same numbers. For more robust programming experience, we save the data in files and supply to the code, when needed. However, that requires the code to read files.
The following program reads the file named ‘fn’ and print its first line on the screen. The functions we learn here are open and readline.
f = open('fn', 'r')
line = f.readline()
print(line)
18.6 Writing in a file
The following program creates a file named ‘myfile’ and write - hi, my name is john - in it.
f = open('myfile', 'w')
f.write("hi, my name is john\n")
18.6.1 Example
f=open('stored_pw', 'r')
lines=f.readlines()
login={}
for i in list:
s=i.split()
login[s[0]]=s[1]
user = input("Enter a Username:")
password = input("Enter a Password:")
check that the username is non-zero
if (len(user)>0) and (password==login[user]):
print("login successful")
elif (user not in login):
print("username not found")
else:
print("incorrect password")