Non-Programmer'sTutorial for Python 3/File IO
来源:互联网 发布:伤感的网络歌曲 编辑:程序博客网 时间:2024/06/04 18:53
File I/O
Hereis a simple example of file I/O (input/output):
# Write a file
with open("test.txt", "wt")as out_file:
out_file.write("This Text is going toout file\nLook at it and see!")
# Read a file
with open("test.txt", "rt")as in_file:
text = in_file.read()
print(text)
Theoutput and the contents of the filetest.txt
are:
ThisText is going to out file
Look at it and see!
Noticethat it wrote a file calledtest.txt
in the directory that you ran the program from. The\n
in the string tells Python to put anewlinewhere it is.
Anoverview of file I/O is:
Get a file object with the
open
functionRead or write to the file object (depending onhow it was opened)
Ifyou did not use
with
to open the file, you'd have to close it manually
Thefirst step is to get a file object. The way to do this is to use theopen
function. The format is file_object= open(filename, mode)
wherefile_object
is the variable to put the file object, filename
is a string with the filename, andmode
is"rt"
toreada file astextor"wt"
towritea file astext(and a few others we will skip here). Next the file objects functionscan be called. The two most common functions areread
andwrite
.Thewrite
function adds a string to the end of the file. Theread
function reads the next thing in the file and returns it as a string.If no argument is given it will return the whole file (as done in theexample).
Nowhere is a new version of the phone numbers program that we madeearlier:
def print_numbers(numbers):
print("Telephone Numbers:")
for k, v in numbers.items():
print("Name:", k,"\tNumber:", v)
print()
def add_number(numbers, name, number):
numbers[name] = number
def lookup_number(numbers, name):
if name in numbers:
return "The number is " +numbers[name]
else:
return name + " was not found"
def remove_number(numbers, name):
if name in numbers:
del numbers[name]
else:
print(name," was not found")
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, number = in_line.split(",")
numbers[name] = number
in_file.close()
def save_numbers(numbers, filename):
out_file = open(filename, "wt")
for k, v in numbers.items():
out_file.write(k + "," + v +"\n")
out_file.close()
def print_menu():
print('1. Print Phone Numbers')
print('2. Add a Phone Number')
print('3. Remove a Phone Number')
print('4. Lookup a Phone Number')
print('5. Load numbers')
print('6. Save numbers')
print('7. Quit')
print()
phone_list = {}
menu_choice = 0
print_menu()
while True:
menu_choice = int(input("Type in anumber (1-7): "))
if menu_choice == 1:
print_numbers(phone_list)
elif menu_choice == 2:
print("Add Name and Number")
name = input("Name: ")
phone = input("Number: ")
add_number(phone_list, name, phone)
elif menu_choice == 3:
print("Remove Name and Number")
name = input("Name: ")
remove_number(phone_list, name)
elif menu_choice == 4:
print("Lookup Number")
name = input("Name: ")
print(lookup_number(phone_list, name))
elif menu_choice == 5:
filename = input("Filename toload: ")
load_numbers(phone_list, filename)
elif menu_choice == 6:
filename = input("Filename tosave: ")
save_numbers(phone_list, filename)
elif menu_choice == 7:
break
else:
print_menu()
print("Goodbye")
Noticethat it now includes saving and loading files. Here is some output ofmy running it twice:
1.Print Phone Numbers
2.Add a Phone Number
3.Remove a Phone Number
4.Lookup a Phone Number
5.Load numbers
6.Save numbers
7.Quit
Typein a number (1-7): 2
AddName and Number
Name:Jill
Number:1234
Typein a number (1-7): 2
AddName and Number
Name:Fred
Number:4321
Typein a number (1-7): 1
TelephoneNumbers:
Name:Jill Number: 1234
Name:Fred Number: 4321
Typein a number (1-7): 6
Filenameto save: numbers.txt
Typein a number (1-7): 7
Goodbye
1.Print Phone Numbers
2.Add a Phone Number
3.Remove a Phone Number
4.Lookup a Phone Number
5.Load numbers
6.Save numbers
7.Quit
Typein a number (1-7): 5
Filenameto load: numbers.txt
Typein a number (1-7): 1
TelephoneNumbers:
Name:Jill Number: 1234
Name:Fred Number: 4321
Typein a number (1-7): 7
Goodbye
Thenew portions of this program are:
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, number = in_line.split(",")
numbers[name] = number
in_file.close()
def save_numbers(numbers, filename):
out_file = open(filename, "wt")
for k, v in numbers.items():
out_file.write(k + "," + v +"\n")
out_file.close()
Firstwe will look at the save portion of the program. First it creates afile object with the commandopen(filename,"wt")
. Next it goesthrough and creates a line for each of the phone numbers with thecommandout_file.write(k+ "," + v + "\n")
.This writes out a line that contains the name, a comma, the numberand follows it by a newline.
Theloading portion is a little more complicated. It starts by getting afile object. Then it uses awhileTrue:
loop to keep looping untilabreak
statement is encountered. Next it gets a line with the linein_line= in_file.readline()
. Thereadline
function will return an empty string when the end of the file isreached. The if
statement checks for this andbreak
sout of thewhile
loop when that happens. Of course if thereadline
function did not return the newline at the end of the line therewould be no way to tell if an empty string was an empty line or theend of the file so the newline is left in what readline
returns. Hence we have to get rid of the newline. The linein_line= in_line[:-1]
does this for usby dropping the last character. Next the linename,number = in_line.split(",")
splits the line at the comma into a name and a number. This is thenadded to thenumbers
dictionary.
Advanced use of .txt files
Youmight be saying to yourself, "Well I know how to read and writeto a textfile, but what if I want to print the file without openingout another program?"
Thereare a few different ways to accomplish this. The easiest way doesopen another program, but everything is taken care of in the Pythoncode, and doesn't require the user to specify a file to be printed.This method involves invoking the subprocess of another program.
Rememberthe file we wrote output to in the above program? Let's use thatfile. Keep in mind, in order to prevent some errors, this programuses concepts from the Next chapter. Please feel free to revisit thisexample after the next chapter.
import subprocess
def main():
try:
print("This small program invokesthe print function in the Notepad application")
#Lets print the file we created in theprogram above
subprocess.call(['notepad','/p','numbers.txt'])
except WindowsError:
print("The called subprocess doesnot exist, or cannot be called.")
main()
Thesubprocess.call
takes three arguments. The first argument in the context of thisexample, should be the name of the program which you would like toinvoke the printing subprocess from. The second argument should bethe specific subprocess within that program. For simplicity, justunderstand that in this program,'/p'
is the subprocess used to access your printer through the specifiedapplication. The last argument should be the name of the file youwant to send to the printing subprocess. In this case, it is the samefile used earlier in this chapter.
- Non-Programmer'sTutorial for Python 3/File IO
- python file io 详解
- python Non-ASCII character '\xe5' in file
- MongoDB for Java Programmer ——3
- Cellular Automaton-Python for Programmer : UC Berkeley SelfPace Course
- specifies a non-existent file for the CFBundleExecutable key
- error: ... specifies a non-existent file for the CFBundleExecutable
- new io for Chinse file path
- python 遇到 syntaxerror: non-ascii character '/xd6' in file
- python SyntaxError: Non-ASCII character '\xe7' in file解决方法
- python:Non-ASCII character ‘\xe2′ in file
- python报:SyntaxError: Non-ASCII character '\xe5' in file
- Python异常:SyntaxError: Non-ASCII character '\xe4' in file...解析
- python 遇到 syntaxerror: non-ascii character '/xd6' in file
- 【Python】【Error】syntaxerror non-ascii character ' xb4' in file
- python:Non-ASCII character 'xe5' in file报错问题
- 解决Python中SyntaxError: Non-ASCII character '\xe7' in file
- python syntaxerror non ascii character xe5 in file
- 使用openface训练自己的第一个模型
- 机器学习编程作业(exe1)总结
- Linux下/proc目录下文件分析
- ASP.NET缓存之数据库缓存依赖(二)
- spring bean的生命周期
- Non-Programmer'sTutorial for Python 3/File IO
- Python File I/O
- 洛谷 P1462 通往奥格瑞玛的道路
- 4个数字凑最大时间
- 第五章 5.5 跳转语句
- 机房收费系统—登录
- android View Animation之Tween animation
- 【JZ雅礼联考】斐波那契 题解
- 引入思考的电影电视动漫