python file operations

python_files_operations

files, file objects
open(name [, mode [, bufsize]])

eg:
file = "data.txt"
f = open(file, ‘r‘)
f = open(file, ‘w‘)
  • ‘r‘:read
  • ‘w‘:write
  • ‘a‘:append
  • ‘rb‘:write binary,在unix中文件都可以当作二进制,所以都用‘rb‘
  • ‘U‘ or ‘rU‘: 提供通用支持给换行符,可以写跨平台执行的文件

换行符在windows中为‘\r\n‘, 在unix中为‘\n‘

methods
  • f.read([n]): read at most n bytes
  • f.readline([n]): 每行最多读n个
  • f.readlines([size])
  • f.write(string): 将string写到f中
  • f.writelines(lines)
  • f.close()
  • f.tell(): returns the cur pointer
  • f.seek()

文件对象的一些属性:

  • f.closed: 如果文件是打开的返回False
  • f.mode
  • f.name
  • f.softspace
  • f.newlines
  • f.encoding

遍历文件的方式:

# method 1
while True:
    line = f.readline()
        if not line:
            break

# method 2
for line in f:
    # process line
sys.stdin, sys.stout, sys.stderr

stdin映射到用户的键盘输入,stdout和stderr输出文本到屏幕 eg:

import sys
sys.stdout.write("enter your name: ")
name = sys.stdin.readline()

上面的等价与raw_input():

name = raw_input("enter your name: ")

raw_input读取的时候不会包括后面的换行符,这点与stdin.readline()不同

print语句中可以用‘,‘来表示不用输出换行符:

print 1, 2, 3, 4
#等价与
print 1,2,
pirnt 3,4
formatted output
print "The values are %d %7.5f %s" % (x, y, z)
print "The values are {0:d} {1:7.5f} {2}".format(x,y,z)

python3里面,print作为一个函数的形式,如下:

pirnt("the values are", x, y, z, end = ‘‘)

如果要重定向输出到文件中,python2中如下:

f = open("output.txt", "w")
print >>f, "hello world"
...
f.close()

在python3里面,可以直接通过print()函数完成:

print("the values are", x,x,z, file = f)

也可以设置元素之间的分隔符:

print("the values are", x, y, z, sep = ‘,‘)
‘‘‘的使用

‘‘‘可以用来做一些格式化的输出,如:

form = """Dear %(name)s,

Please send back my %(item)s or pay me $%(amount)0.2f.
                                Sincerely yours,
                                Joe Python User

"""
print form % {
              ‘name‘: ‘Mr. Bush‘,
              ‘item‘: ‘blender‘,
              ‘amount‘: 50.00,
}

将会输出

Dear Mr. Bush,

Please send back my blender or pay me $50.00.
                                Sincerely yours,
                                Joe Python User

注意第一行‘‘‘之后的/表示第一行的那个换行符不要了,否则在前面会多输出一个空行。()里面的关键字将会被替换。

用format()函数也可以达到同样的效果:

form = ‘‘‘Dear {name}s,

Please send back my {item}s or pay me ${amount:0.2f}.
                                Sincerely yours,
                                Joe Python User

‘‘‘

print form.format(name = "Jack", item = "blender", amount = 50)

还有string里面的Template函数:

import string
form = string.Template("""Dear $name,
Please send back my $item or pay me $amount.
                    Sincerely yours,
                    Joe Python User
""")
print form.substitute({‘name‘: ‘Mr. Bush‘,
‘item‘: ‘blender‘,
‘amount‘: "%0.2f" % 50.0})

这里用$表示将要被替换的内容

时间: 2024-08-06 03:45:46

python file operations的相关文章

Python File I/O

File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use file

[改]在windows右键菜单中加入“新建Python File文件”并创建模板

1.首先写好模板文件,随便保存在一个地方,比如我是"D:\Python27\foo.py"; 2.打开注册表(regedit),找到 [HKEY_CLASSES_ROOT] -> [.py] (没有的话,自己新建项.py); 3.在 [.py] 下新建项 [ShellNew] (已经有的话就删掉重建); 4.在 [ShellNew] 下新建 字符串值 ,名称为 FileName ,键值为模板文件的绝对路径,比如我的是 D:\Python27\foo.py ; 在右键新建菜单中就会

Python - File - 第十八天

Python File(文件) 方法 open() 方法 Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError. 注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法. open() 函数常用形式是接收两个参数:文件名(file)和模式(mode). open(file, mode='r') 完整的语法格式为: open(file, mode='r', bufferi

python file模块 替换输入内容脚本

1 [email protected]:/home/liujianzuo/python/test# ls 2 passwd rc.local test1 3 [email protected]:/home/liujianzuo/python/test# py test1 -r EXIT exit /home/liujianzuo/python/test/rc.local 4 共修改了0行. 5 [email protected]:/home/liujianzuo/python/test# py

Python:file (read,readline,readline )使用方法

Python读取文件时,在使用readlin.readlines时会有疑惑,下面给大家详解:一.例:a.txt的内容为    aaa 123    bbb 456二.首先我先设置个变量:    a="a.txt"    c=file(a)三.此时我们分别看下使用read.readline.readlines 的读取结果:  (1).read:        IN: c.read()        OUT: ''      SO: read每次读取文件时,通常将读取到底文件内容放到一个字

Python file 方法

#!/usr/bin/env python # *_* coding=utf-8 *_* """ desc: 文件方法 ############################# file.read()         #read([size]) -> read at most size bytes, returned as a string. file.readline()     readline([size]) -> next line from the f

python file

1 >>> help(open) 2 Help on built-in function open in module __builtin__: 3 4 open(...) 5 open(name[, mode[, buffering]]) -> file object 6 7 Open a file using the file() type, returns a file object. This is the 8 preferred way to open a file. S

python {File "<stdin>", line 1} error

学习Python时,第一个程序hello.py(如下) print("hello welcome to python world") 运行报上图错误,是因为已经命令行指示已经运行了Python解释器,注意区分命令行环境和Python交互环境,如下图,直接输入python进入交互模式,即出现>>>是进入了Python交互环境,相当于启动了Python解释器,等待你一行一行地输入源代码,每输入一行就执行一行.而现在是已经写好了.py文件,想要一次性执行完全部的源代码,应该

python file and stream

from sys import stdout ,stdin f=open(r"c:\text\somefile.txt") open(filename,mode,buffering) mode 'r' read 'w' writ 'a' 追加模式 'b' 二进制模式 '+' 读写模式 buffering 0 / False   无缓冲,直接读写 硬盘 1 / True     缓冲,用内存代替硬盘,只有在close/flush才更新硬盘数据 -1 表示使用默认缓冲区 大于1  表示缓冲