Python_day_07_File operations

1. Format

f = open(filename[, mode])
print f.tell()  ##查看当前索引位置
print f.read()  ##读取
f.close()   ##结束

2. File open mode

r:
    文件不存在时,error;
    只能r,不能w;
r+:
    文件不存在时, error;
    可以读写;
    在打开文件时, 不会清除文件原有内容;
w:
    只能w,不能读
    文件不存在时, 创建该文件;
    在打开文件时, 清除文件原有内容;
w+:
    可以读写;
    文件不存在时, 创建该文件;
    在打开文件时, 清除文件原有内容;
a:
    文件不存在时, 创建该文件;
    在打开文件时, 不清除文件原有内容;
    不能读取,只能w;
a+:
    文件不存在时, 创建该文件;
    在打开文件时, 不清除文件原有内容;
    可以读写;

If reading and writing binary data, add b after the original mode;

r, rb; r+, rb+; w, wb; w+, wb+; a, ab; a+, ab+;

f.seek usage

f.write('java')
seek方法需要传两个参数:
     1). 第一个参数: 偏移量;偏移量>0,代表向右偏移, 反之,向左偏移; =0,不偏移;
     2). 0: 文件开头; 1代表当前位置; 2代表文件末尾;
f.seek(3,0)
print f.tell()  
print f.read()  
f.close()

3.os module

import os

1)os.path

myFiles = ['account.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
    print os.path.join('/tmp/', filename)   ##路径连接
结果为
/tmp/account.txt
/tmp/details.csv
/tmp/invite.docx

print os.path.abspath('hello')          ##当前文件绝对路径
print os.path.isabs('/home/kiosk/Desktop/untitled/hello')   ##当前路径绝对路径是否为,返回布尔值
print os.path.dirname('/etc/passwd')        ##文件路径上层目录(除了当前底层目录)
print os.path.basename('/etc/password')     ##文件路径底层目录
print os.path.split('/etc/passwd/aa')       ##将文件路径分块(上层和底层)
print 'etc/passwd/aa'.split(os.path.sep)    ##将文件路径全部分块
print os.path.sep               ##相当于分隔符 /
print os.path.getsize('/etc/passwd')        ##文件大小
print os.listdir('/mnt')            ##列出
print os.path.exists('/etc/passwd')     ##判断是否存在,返回布尔值

2) os.getcwd / os.chdir ##Location directory query / change path

print os.getcwd()
os.chdir('/mnt')
print os.getcwd()

3) os.makedirs ##Create directory

os.makedirs('/tmp/hello01')

4)shelve

Shelve is python's own model, which can be directly referenced by import shelve.
Shelve is similar to a persistent dictionary that stores persistent objects, that is, a dictionary file.
The usage method is also similar to a dictionary.

import shelve

devin = dict(name='devin')
tom = dict(name='tom')
op = shelve.open('/mnt/123')
op['devin'] = devin
op['tom'] = tom
print op
print op['devin']
op.close()

#4.文件读取
from collections import Iterable
f = open('/mnt/passwd', 'r')
print f.readable()  ??

print f.readline()  ##显示一行内容
print f.readline()
print f.readline()
** strip去除\n,\t,
print [line.strip() for line in f.readlines()]
print type(f)       ##file 类型
f.close()

print isinstance(f, Iterable)
for i in f:         # 迭代器,open文件内容可迭代
    print i

5. File writing

users = [
    'user1:passwd:westos',
    'user2:passwd2:westos',
    'user3:passwd3:westos',
]

users = [user + '\n' for user in users]

f = open('/tmp/passwd.swp', 'w+')
f.write('hello world')  ##单行写入
f.writelines(users) ##多行写入
f.seek(0, 0)
print f.read()
f.close()


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326042509&siteId=291194637