前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2017/6/9-Python文件读写的方法

2017/6/9-Python文件读写的方法

作者头像
致Great
发布2018-04-11 17:28:17
7020
发布2018-04-11 17:28:17
举报
文章被收录于专栏:程序生活程序生活
# 使用斜杠“/”: "c:/test.txt"… 不用反斜杠就没法产生歧义了 
# 将反斜杠符号转义: "c:\\test.txt"… 因为反斜杠是转义符,所以两个"\\"就表示一个反斜杠符号 
# file=open('D:\\jupyter\\test.txt')#
#file=open('D:/jupyter/test.txt')
#file=open('test.txt')#和程序在一个同一路径下
file=open('test.txt')
file.read()
'hi quincyqiang\nhow are you'
#模式描述
# http://www.yiibai.com/python3/python_files_io.html

# 读文件有3种方法:read()将文本文件所有行读到一个字符串中。 
#               readline()是一行一行的读 
#               readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。 
# 优点:readline()可以在读行过程中跳过特定行。 \

#第一种方法
file_1=open('test.txt')
file_2=open('output.txt','w')
while True:
    line=file_1.readline()
    print(line.strip())#取出换行
    file_2.write(line) 
    if not line:
        break
file_2.close()
hi quincyqiang
how are you
#第二种方法,使用for循环
file_2=open('output.txt','w')
for line in open('test.txt'):
    print(line.strip())
    file_2.write(line)
file_2.close()
hi quincyqiang
how are you
#第三种方法文件上下文
文件上下文管理器 
with open('somefile.txt', 'r') as f: 
    data = f.read() 

# Iterate over the lines of the file 
with open('somefile.txt', 'r') as f: 
    for line in f: 
        # process line 

# Write chunks of text data 
with open('somefile.txt', 'w') as f: 
    f.write(text1) 
    f.write(text2) 
    ... 

# Redirected print statement 
with open('somefile.txt', 'w') as f: 
    print(line1, file=f) 
    print(line2, file=f)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.06.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
NLP 服务
NLP 服务(Natural Language Process,NLP)深度整合了腾讯内部的 NLP 技术,提供多项智能文本处理和文本生成能力,包括词法分析、相似词召回、词相似度、句子相似度、文本润色、句子纠错、文本补全、句子生成等。满足各行业的文本智能需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档