Fork me on GitHub

py基础三

python基础语法(三)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!usr/bin/python
# -*- coding: UTF-8 -*-
#打开一个文件
fo= open("4.txt", "r+")
#fo.write( "www.runoob.com!\nVery good site!\n");
str= fo.read(10)
print "文件名: ", fo.name
print "是否已关闭: ", fo.closed
print "访问模式: ", fo. mode
print "末尾是否强制加空格: ", fo.softspace
print "读取的字符串是: ", str
position= fo.tell()
print "当前文件位置: ", position
position= fo.seek(0, 0)
str= fo.read(10)
print "重新读取字符串: ", str
fo.close()
#重命名文件
import os
os.rename("4.txt", "1.txt")
#删除文件
os.remove("1.txt")
#创建目录
os.mkdir("test")
#改变目录
#将当前目录改为"/home/newdir"
os.chdir("/home/newdir")
#显示当前目录
os.getcwd()
#删除目录
os.rmdir("/tmp/test")
#在 write 内容后,直接 read 文件输出会为空,是因为指针已经在内容末尾。
#两种解决方式: 其一,先 close 文件,open 后再读取,其二,可以设置指针回到文件最初后再 read
document = open("testfile.txt", "w+");
print "文件名: ", document.name;
document.write("这是我创建的第一个测试文件!\nwelcome!");
print document.tell();
#输出当前指针位置
document.seek(os.SEEK_SET);
#设置指针回到文件最初
context = document.read();
print context;
document.close();

Your support will encourage me to continue to create!