栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python读写文件操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python读写文件操作

python读取本地文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-

#方法1
with open('stu.txt') as f:
        #print(f.readlines())
        for line in f.readlines():
                line = line.strip('n').split('t')[0]
                print(line)

#方法2
f = open("stu.txt","r")
arr = f.readlines()
print(arr)
python写数据到本地文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 1.打开txt文件
Note=open('x.txt',mode='w')
# 函数=open(x.扩展名,mode=模式)
# w       只能操作写入(如果而文件中有数据,再次写入内容,会把原来的覆盖掉)
# r        只能读取
# a       向文件追加
# w+     可读可写
# r+      可读可写
# a+     可读可追加
# wb+   写入数据

# 2.向文件中写入数据
# 第一种写入方式:write 写入
Note.write('hello word 你好 n') #n 换行符

# 第二种写入方式:writelines 写入行
# writelines()将列表中的字符串写入文件中,但不会自动换行,换行需要添加换行符
# writelines()只存放字符串的列表
Note.writelines(['hellon','worldn','你好n','CSDNn','威武n']) #n 换行符

# 3.关闭文件
Note.close()
读写整合(读本地文件,处理数据后,写到本地)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 将文件中的学生名获取到并写入另一个文件
# zhangsan	21	北京		==》	zhangsan
Note=open('r.txt',mode='a')
with open('stu.txt') as f:
        for line in f.readlines():
                line = line.strip('n').split('t')[0]
                print(line)
                Note.write(line+'n')

Note.close()

参考文档:
https://blog.csdn.net/HoyAnGx/article/details/124835576
https://www.csdn.net/tags/MtjaMgxsMTYwLWJsb2cO0O0O.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号