File I/O

Here is 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 to
out file\nLook at it and see!")

# Read a file
with open("test.txt", "rt")
as in_file:
    text = in_file.read()

print(text)

The output and the contents of the file test.txt are:

This
Text is going to out file
Look at it and see!

Notice that it wrote a file called test.txt in the directory that you ran the program from. The \n in the string tells Python to put a newline where it is.

An overview of file I/O is:

  • Get a file object with the open function

  • Read or write to the file object (depending on how it was opened)

  • If you did not use with to open the file, you'd have to close it manually

The first step is to get a file object. The way to do this is to use the open function. The format is file_object = open(filename, mode) where file_object is the variable to put the file object, filename is a string with the filename, and mode is "rt" to read a file as text or "wt" to write a file as text (and a few others we will skip here). Next the file objects functions can be called. The two most common functions are read and write. The write function adds a string to the end of the file. The read 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 the example).

Now here is a new version of the phone numbers program that we made earlier:

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 a
number (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 to
load: ")
        load_numbers(phone_list, filename)
    elif menu_choice == 6:
        filename = input("Filename to
save: ")
        save_numbers(phone_list, filename)
    elif menu_choice == 7:
        break
    else:
        print_menu()

print("Goodbye")

Notice that it now includes saving and loading files. Here is some output of my 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

Type
in a number (1-7): 2
Add
Name and Number
Name:
Jill
Number:
1234
Type
in a number (1-7): 2
Add
Name and Number
Name:
Fred
Number:
4321
Type
in a number (1-7): 1
Telephone
Numbers:
Name:
Jill Number: 1234
Name:
Fred Number: 4321

Type
in a number (1-7): 6
Filename
to save: numbers.txt
Type
in 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

Type
in a number (1-7): 5
Filename
to load: numbers.txt
Type
in a number (1-7): 1
Telephone
Numbers:
Name:
Jill Number: 1234
Name:
Fred Number: 4321

Type
in a number (1-7): 7
Goodbye

The new 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()

First we will look at the save portion of the program. First it creates a file object with the command open(filename, "wt"). Next it goes through and creates a line for each of the phone numbers with the command out_file.write(k + "," + v + "\n"). This writes out a line that contains the name, a comma, the number and follows it by a newline.

The loading portion is a little more complicated. It starts by getting a file object. Then it uses a while True: loop to keep looping until a break statement is encountered. Next it gets a line with the line in_line = in_file.readline(). The readline function will return an empty string when the end of the file is reached. The if statement checks for this and breaks out of the while loop when that happens. Of course if the readline function did not return the newline at the end of the line there would be no way to tell if an empty string was an empty line or the end of the file so the newline is left in what readline returns. Hence we have to get rid of the newline. The line in_line = in_line[:-1] does this for us by dropping the last character. Next the line name, number = in_line.split(",") splits the line at the comma into a name and a number. This is then added to the numbers dictionary.

Advanced use of .txt files

You might be saying to yourself, "Well I know how to read and write to a textfile, but what if I want to print the file without opening out another program?"

There are a few different ways to accomplish this. The easiest way does open another program, but everything is taken care of in the Python code, and doesn't require the user to specify a file to be printed. This method involves invoking the subprocess of another program.

Remember the file we wrote output to in the above program? Let's use that file. Keep in mind, in order to prevent some errors, this program uses concepts from the Next chapter. Please feel free to revisit this example after the next chapter.

import subprocess
def main():
    try:
        print("This small program invokes
the print function in the Notepad application")
        #Lets print the file we created in the
program above
subprocess.call(['notepad','/p','numbers.txt'])
    except WindowsError:
        print("The called subprocess does
not exist, or cannot be called.")

main()

The subprocess.call takes three arguments. The first argument in the context of this example, should be the name of the program which you would like to invoke the printing subprocess from. The second argument should be the specific subprocess within that program. For simplicity, just understand that in this program, '/p' is the subprocess used to access your printer through the specified application. The last argument should be the name of the file you want to send to the printing subprocess. In this case, it is the same file used earlier in this chapter.

Non-Programmer's Tutorial for Python 3/File IO的更多相关文章

  1. 【Python】File IO

    1.numpy.genfromtxt() numpy.genfromtxt() CSV文件很容易被numpy类库的genfromtxt方法解析 2.

  2. 转发 python中file和open有什么区别

    python中file和open有什么区别?2008-04-15 11:30地痞小流氓 | 分类:python | 浏览3426次python中file和open有什么区别?都是打开文件,说的越详细越 ...

  3. python爬取豆瓣小组700+话题加回复啦啦啦python open file with a variable name

    需求:爬取豆瓣小组所有话题(话题title,内容,作者,发布时间),及回复(最佳回复,普通回复,回复_回复,翻页回复,0回复) 解决:1. 先爬取小组下,所有的主题链接,通过定位nextpage翻页获 ...

  4. Python模块File文件操作

    Python模块File简介 Python提供了File模块进行文件的操作,他是Python的内置模块.我们在使用File模块的时候,必须先用Popen()函数打开一个文件,在使用结束需要close关 ...

  5. python 网络编程 IO多路复用之epoll

    python网络编程——IO多路复用之epoll 1.内核EPOLL模型讲解     此部分参考http://blog.csdn.net/mango_song/article/details/4264 ...

  6. python网络编程——IO多路复用之select

    1 IO多路复用的概念 原生socket客户端在与服务端建立连接时,即服务端调用accept方法时是阻塞的,同时服务端和客户端在收发数据(调用recv.send.sendall)时也是阻塞的.原生so ...

  7. Python之模块IO

    目录 Python之模块IO io概叙 io类层次结构 io模块的类图 io模块的3种I/O 原始I/O,即RawIOBase及其子类 文本I/O,即TextIOBase及其子类 字节I/O(缓存I/ ...

  8. Python基础之:Python中的IO

    目录 简介 linux输入输出 格式化输出 f格式化 format格式化 repr和str %格式化方法 读写文件 文件对象的方法 使用json 简介 IO就是输入和输出,任何一个程序如果和外部希望有 ...

  9. Linux Kernel File IO Syscall Kernel-Source-Code Analysis(undone)

    目录 . 引言 . open() syscall . close() syscall 0. 引言 在linux的哲学中,所有的磁盘文件.目录.外设设备.驱动设备全部被抽象为了"文件" ...

随机推荐

  1. kubernetes容器编排系统介绍

    版权声明:本文由turboxu原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/152 来源:腾云阁 https://www. ...

  2. 在cocos code ide的基础上构建自己的lua开发调试环境

    对于一种语言,其所谓开发调试环境, 大体有以下两方面的内容: 1.开发, 即代码编写, 主要是代码提示.补齐, 更高级一点的如变量名颜色等. 2.调试, 主要是运行状态下断点.查看变量.堆栈等. 现在 ...

  3. TWaver HTML5 (2D)--基本概念

    基本概念 TWaver HTML5(以下简称TWaver)使用HTML5技术和javascript语言,可在支持HTML5的浏览器上进行绘图. 使用TWaver前,需熟悉几个基本概念:图元(Eleme ...

  4. servlet的配置和上下文

    一.Servlet配置对象(ServletConfig):Servlet初始化时,容器调用其init(ServletConfig)方法,传递该对象. 1.获得对象方法: (1).直接使用getServ ...

  5. prepareStatement和Statement的区别

    1:创建时的区别:    Statement stm=con.createStatement();    PreparedStatement pstm=con.prepareStatement(sql ...

  6. Struts2配置拦截器,struts2加载常量时的搜索顺序

    1:struts2加载常量时的搜索顺序 1.Struts-default.xml 2.Struts-plugin.xml 3.Struts.xml 4.Struts-properties(自己创建的) ...

  7. jquery中ajax常用方法

    index.html: <h3>$.get(url, [data], [callback], [type])<br/> $.post(url, [data], [callbac ...

  8. [转]POJO中使用ThreadLocal实现Java嵌套事务

    大多嵌套事务都是通过EJB实现的,现在我们尝试实现对POJO的嵌套事务.这里我们使用了ThreadLocal的功能. 理解嵌套事务 事务是可以嵌套的.所以内层事务或外层事务可以在不影响其他事务的条件下 ...

  9. js中获得当前时间是年份和月份

    js中获得当前时间是年份和月份,形如:201208       //获取完整的日期 var date=new Date; var year=date.getFullYear();  var month ...

  10. freemarker实例2

    下面演示一个简单的使用项目过程:1. 使用myeclipse创建一个web项目testFM2. 把下载到的jar包(freemarker-2.3.9.jar)放到/WebRoot/WEB-INF/li ...