当前位置:   article > 正文

python读写文件操作_note.writelines

note.writelines

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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(['hello\n','world\n','你好\n','CSDN\n','威武\n']) #\n 换行符

# 3.关闭文件
Note.close()
  • 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

读写整合(读本地文件,处理数据后,写到本地)

#!/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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/820447
推荐阅读
相关标签
  

闽ICP备14008679号