hadoop学习之hive

1.文件读取的三种方法

方法一:

代码如下:

f = open("foo.txt")             # 返回一个文件对象  
line = f.readline()             # 调用文件的 readline()方法  
while line:  
    print line,                 # 后面跟 ',' 将忽略换行符  
    # print(line, end = '')   # 在 Python 3中使用  
    line = f.readline()  

f.close()  

方法二:

复制代码 代码如下:

for line in open("foo.txt"):  
    print line,  

方法三:

复制代码 代码如下:

f = open("c:\\1.txt","r")  
lines = f.readlines()#读取全部内容  
for line in lines  
    print line 


wirte()方法把字符串写入文件,writelines()方法可以把列表中存储的内容写入文件。

f=file("hello.txt","w+")

li=["hello world\n","hello china\n"]

f.writelines(li)

f.close()


文件的内容:

hello world

hello china

write()和writelines()这两个方法在写入前会清除文件中原有的内容,再重新写入新的内容,相当于“覆盖”的方法。如果需要保留文件中原有的内容,只是需要追加新的内容,可以使用“a+”模式

打开文件。


f=file("hello.txt","a+")

new_context="goodbye"

f.write(new_content)

f.close()

此时hello.txt中的内容如下所示:

hello world

hello china

goodbye


实践:

>>> f=file("hello.txt","w+")
>>> li=["hello world\n","hello china\n"]
>>> f.writelines(li)
>>> f.close()
>>> 
>>> f=file("hello.txt","a+")
>>> new_context="goodbye"

>>> f.write(new_content)
>>> f.write(new_content)
>>> f.close()

结果:

hello world
hello china
goodbyegoodbye

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值