【3.8】python读写数据

这几天不停的在用Python读写数据,索性就整理一下python的一些数据读写方面的东西。先打个框架,不停的补内容吧。

python的基本输入机制是基于行的,一次读取一行数据

import os
os.chdir('E:\\py\\chapter4')  #更改工作路径,注意这个win下的写法
os.getcwd()   #这个是获得当前工作路径,

一、读数据

1.open()函数

open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

file_object = open('thefile.txt','r')   #默认位‘r’,可以删掉
try:
   all_the_text = file_object.read( )
finally:
   file_object.close( )

注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

读二进制文件

input = open('data', 'rb')

读取所有内容

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

如果文件是文本文件,还可以直接遍历文件对象获取每行:

for line in file_object:
	process line

print(data.readline(),end='') #一次读取一行数据

data.seek(0) #回到第一行数据

data = open('sketch.txt')
for each_line in data:
    if not each_line.find(':') == -1:
        (role, line_spoken) = each_line.split(':', 1)
        print(role, end='')
        print(' said ', end='')
        print(line_spoken, end='')
data.close()

#find()用来找是否存在什么,用在上面作为查错机制, #each_line.split(':', 1),其中的1表示数据分解为两部分。

加入try,except来容许出错。

data = open('sketch.txt')
for each_line in data:
    try:
        (role, line_spoken) = each_line.split(':', 1)
        print(role, end='')
        print(' said: ', end='')
        print(line_spoken, end='')
    except:
        pass
data.close()

检查文件是否存在

import os
if os.path.exists('sketch.txt'):
    data = open('sketch.txt')
    for each_line in data:
        if not each_line.find(':') == -1:
            (role, line_spoken) = each_line.split(':', 1)
            print(role, end='')
            print(' said: ', end='')
            print(line_spoken, end='')
    data.close()
else:
print('The data file is missing!')

二、写数据

写文件写文本文件output = open('data.txt', 'w')
 写二进制文件output = open('data.txt', 'wb')
 追加写文件output = open('data.txt', 'a')
 output .write("\n都有是好人")
 output .close( )

file_object = open('thefile.txt', 'w')
 file_object.write(all_the_text)
 file_object.close( )

例子:

man = []
other = []
try:
    data = open('sketch.txt')	 
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print('The datafile is missing!')

用with可以省略close()

try:
    man_file = open('man_data.txt', 'w')
    other_file = open('other_data.txt', 'w')
    print(man, file=man_file)
    print(other, file=other_file)
    man_file.close()
    other_file.close()
except IOError:
print('File error.')


man = []
other = []
try:
    data = open('sketch.txt')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':')
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
            else:
                pass
        except ValueError:
            pass 
    data.close()
except IOError:
    print('The datafile is missing!')

 

try:
    with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
        print(man, file=man_file)
        print(other, file=other_file)

except IOError as err:
print('File error: ' + str(err))

指定输出的格式

import sys

"""This is the "nester.py" module and it provides one function called print_lol()

   which prints lists that may or may not include nested lists."""

def print_lol(the_list, indent=False, level=0, fh=sys.stdout):

    """ Prints a list of (possibly) nested lists.
 
        This function takes a positional argument called "the_list", which
        is any Python list (of - possibly - nested lists). Each data item in the provided list is (recursively) printed to the screen on it’s own line.

        A second argument called "indent" controls whether or not indentation is shown on the display. This defaults to False: set it to True to switch on.

        A third argument called "level" (which defaults to 0) is used to insert tab-stops when a nested list is encountered.

        A fourth argument called "fh" identifies the file to write to (which is
        assumed to be opened and writeable to). This defaults to "sys.stdout",
        i.e., standard output."""

    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, indent, level+1, fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t", end='', file=fh)
            print(each_item, file=fh)

参考资料:

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn