Python学习--Python文件操作

1 文件的读取

先在我的E盘文件夹里面创建一个.txt格式的文件,文件名叫做foo。
接下来读取文件。

1.1 读取整个文件

file = open('foo.txt','r') #此时file是一个全局变量
contents = file.read()
print(contents)
file.close()      #需要写colse函数
with open('foo.txt','r') as file: #可以自动关闭文件
    contents = file.read()
    print(contents)

#区别:1变量的范围
#     2文件是否自动关闭

1.2 逐行读取

with open('foo.txt','r') as file: #可以自动关闭文件,逐行读取
    for line in file: 
        print(line.rstrip())

1.3 读取入列表

with open('foo.txt','r') as file: #可以自动关闭文件,逐行读取
    lines = file.readlines()
for line in lines:
    print(line.rstrip())

lines 为列表

2 文件的写入

with open('foo.txt','w') as file:
    file.write('I love python1!\n')
    file.write('I love python2!\n')
    file.write('I love python3!\n')

w权限,覆盖之前的内容。

with open('foo.txt','a') as file:
    file.write('I love python1!\n')
    file.write('I love python2!\n')
    file.write('I love python3!\n')

a权限,在里面追加内容。

读写权限
R+ 不创建新文件,文件读写指针在开头
W+ 创建新文件,读写指针在开头,如果文件存在会覆盖这个文件之前的内容
A+ 创建新文件,读写指针在末尾(因为是追加),不会覆盖之前的内容

3 seek函数和tell函数

File_object.seek(offet,whence)
whence参数:
0表示从开头计算
1表示从当前位置计算
2表示从文件末尾为原点计算

with open('foo.txt','w') as file:
    file.write('www.python.org')
with open('foo.txt','rb+') as file:
    file.seek(0,0)
    print(file.tell())
    file.seek(3,0)
    print(file.tell())
    file.seek(1,1)
    print(file.tell())
    file.seek(1,2)
    print(file.tell())

3 实战用本地文件当作数据库,实现用户的登陆脚本

myfile = open('foo.txt','a')
while True:
    account = input('please input your ID:')
    passwd = input('please input your passwd:')
    str1 = '%s:%s'%(account,passwd)  #格式化保存
    myfile.write(str1)
    myfile.flush()
    print('congratulations')
    break;
myfile.close()

上面代码就可以输入用户信息了。但是还有些小问题需要优化。

登录部分脚本:

myfile = open('foo.txt','a')
while True:
    account = input('please input your ID:')
    if account == '':
        print('please input your ID again!')
        continue
    passwd = input('please input your passwd:')
    if passwd == '':
        print('please input your passwd again!')
        continue
    str1 = '%s:%s\n'%(account,passwd)  #格式化保存
    myfile.write(str1)
    myfile.flush()
    print('congratulations')
    break;
myfile.close()

这样子程序就可以自动换行和防止空输入了。

myfile = open('foo.txt','r')
islogin = 1
oklogin = 0

while True:
    if oklogin == 0:
        if islogin == 4:
            print("三次错误, 再见!")
            break
        else:
            account = input('please input your ID:')
            passwd = input('please input your passwd:')
            for str in myfile:
                file_account = str.split(':')[0] 
                file_passwd = str.split(':')[1]  
                file_passwd = file_passwd[:-1] #切片判断
                if file_account == account and file_passwd == passwd:
                    oklogin = 1
                    break
            islogin += 1
            continue
    else:
        print("congratulations") 
        break
myfile.close()

猜你喜欢

转载自blog.csdn.net/qq_16481211/article/details/80228552