您的位置:首页 > 编程语言 > Python开发

Python 文件操作

2017-04-01 23:37 225 查看

一、Python文件I/O

打印到屏幕

>>> print("Python 是一个非常棒的语言,不是吗?")
Python 是一个非常棒的语言,不是吗?
>>>
>>> import sys
>>> sys.stdout.write("Python 是一个非常棒的语言,不是吗?")
Python 是一个非常棒的语言,不是吗?21
>>>

读取键盘输入

>>> str = input('please input something here: ')     # python3.x 相当于Python2.x的raw_input()
please input something here: something
>>> print('the content you put is : ', str)
the content you put is :  something
>>>

打开和关闭文件

open 函数

你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。

语法:

file object = open(file_name [, access_mode][, buffering])

各个参数的细节如下:

  • file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
  • access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
  • buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

1 #!/usr/local/Python-3.5.2/python
2 # -*- coding:utf-8 -*-
3 # antcolonies
4
5 import sys,os
6
7 filename = sys.argv[1]
8
9 def search(string):
10     flag = ''
11     with open(filename,'r',encoding='utf-8') as f:
12         for line in f:
13             if string in line:
14                 if len(line)==len(line.lstrip()):
15                     flag = True
16             if flag:
17                 print(line.rstrip())
18                 if line.strip() == '':
19                     break
20
21 def create(arg):
22     with open(filename,'r',encoding='utf-8') as f:
23         listfile = f.readlines()
24         lastline = listfile[-1]
25         arg_str = '%s %s %s %d %s %d' %('server',arg['record']['server'],'weight',\
26     arg['record']['weight'],'maxconn',arg['record']['maxconn'])
27         if lastline.strip() == arg_str:
28             print('the record you put has already existed!')
29             return False
30         indent = len(lastline) - len(lastline.lstrip())
31         indentstr = ''
32         for i in range(indent):
33             indentstr += ' '
34         arg_str = '%s%s' %(indentstr,arg_str)
35     with open(filename,'a',encoding='utf-8') as f:
36         f.write('%s%s %s %s %d %s %d' %(indentstr,'server',arg['record']['server'],\
37     'weight',arg['record']['weight'],'maxconn',arg['record']['maxconn']))
38
39
40 def delete(arg):
41     filename_1 = filename + '_1'
42     record = '%s %s %s %d %s %d' %('server',arg['record']['server'],'weight',\
43     arg['record']['weight'],'maxconn',arg['record'][    'maxconn'])
44     with open(filename,'r',encoding='utf-8') as f,\
45     open(filename_1,'w',encoding='utf-8') as f_new:
46         for line in f:
47             if record == line.strip():
48                 continue
49             f_new.write(line)
50     os.rename(filename_1,filename)
51
52
53 while True:
54     action = input('(search|create|delete)')
55     if action == 'search':
56         record = input('select a title: ')
57         search(record)
58     elif action == 'create':
59         arg = input('input an argv: ')
60         arg_list = eval(arg)
61         create(arg_list)
62     elif action == 'delete':
63         arg = input('input an argv: ')
64         arg_list = eval(arg)
65         delete(arg_list)
66     else:
67         print('you put a wrong action!')
68     stat = input("q(quit) or any other keywords to continue: ")
69     if stat == 'q':
70         break
code  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: