码迷,mamicode.com
首页 > 编程语言 > 详细

python学习-35 文件处理

时间:2019-07-10 20:12:53      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:nis   字符串   内容   学习   print   字符   RoCE   另一个   odi   

1.简单的打开文件

f=open(test.txt,encoding=utf-8)    # 打开了名字为test.txt的文件里的内容
data=f.read()                            # 读取里面的内容
print(data)
f.close()

运行结果:

hello,word

Process finished with exit code 0

2.可读性

f=open(test.txt,r,encoding=utf-8)
data=f.readable()        # 是否可读
print(data)
f.close()

运行结果:

True

Process finished with exit code 0

 

3.一行一行读取内容

f=open(test.txt,r,encoding=utf-8)

print(f.readline(),end=‘‘)
print(f.readline())
print(f.readline())
print(4,f.readline())
print(5,f.readline())

f.close()

运行结果:

1.hello,word
2.hello,word

3.hello,word

4 
5 

Process finished with exit code 0

4.读取全部内容

f=open(test.txt,r,encoding=utf-8)


data=f.readlines()
print(data)

f.close()

运行结果:

[1.hello,word\n, 2.hello,word\n, 3.hello,word\n]

Process finished with exit code 0

5.写入操作 (只能是字符串类型)

1.

f=open(test.txt,w,encoding=utf-8)

f.write(1111\n)    # 想换行需要加\n
f.write(222)


f.close()

打开test.txt文件就会看到写入的1111和222

2.写入列表

f=open(test.txt,w,encoding=utf-8)

f.writelines([456\n,123\n,asd\n])   


f.close()

可以打开自己的test.txt文件内容查看

3.追加

f=open(test.txt,a,encoding=utf-8)
f.write(\n123)

4.

f1 = open(test.txt,r,encoding=utf-8)
data = f1.readlines()
f1.close()


f2 = open(test_new.txt,w,encoding=utf-8)  # 新建一个文件
f2.write(data[0])                # 删除除第一行外的其他行,并写入到新文件里
f2.close()

5.

with open(test.txt,w) as f:       # 写入文件并自动关闭,不用手动close()
    f.write(123)

6.从一个文件里读取到 文件 然后写入到另一个文件

with open(test.txt,r,encoding=utf-8) as f,    open(test_new.txt,w,encoding=utf-8) as f1:
    data = f.read()
    f1.write(data)

 

python学习-35 文件处理

标签:nis   字符串   内容   学习   print   字符   RoCE   另一个   odi   

原文地址:https://www.cnblogs.com/liujinjing521/p/11166130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!