python基础篇之基本语法和文件操作

在了解 Python 的基本概念和数据结构后, 再了解一下基本语法来将这些零件合理的组合起来,这样就可以用 Python 干一下复杂的任务了,再熟悉一下文件操作来扩展一下输入输出。

基本语法
条件语句

代码演示

score = 70
if score > 100 :
    print 'the score is out of range.'
elif score > 60 :
    print 'your score is from 60 to 100.'
elif score > 0 :
    print 'your score is from 0 to 60.'
else :
    print 'the score is out of range.'

for循环语句

代码演示

colors = ['red','blue','green']

for color in colors
    print 'color is ' + color
# print the numbers from 0 through 99
for i in range(100):
    print i

while循环语句

代码演示

# list中元素a在哪个位置
i = 0
while i < len(list):
    if list[i] == a :
        print i
        break
    else :
        i += 1

文件操作
Python 处理文件也是有一手的,所以熟练掌握文件操作对日后的任务操作非常有利.

打开/关闭文件

代码演示

# 显示文本
f = open('foo.txt', 'rU')     ## r/w/a同c里面的意义,U代表通用,最终的结尾符转换成'\n'
for line in f:     # 遍历文件的每一行
    print line,    # 紧跟 ,这样print就不会输出换行符,因为line里面就有换行符
f.close()

读写文本

读文本到内存,返回一个 list

f.readlines()

读文本到字符串,返回字符串(配合正则表达式)

f.read()

写数据到输出文件

f.write(string)
print >>f ,string
print(string, file=f)

unicode文本操作

codecs模块支持

import codecs

f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
  # here line is a *unicode* string

# 用f.write()写文件,print不完全支持unicode

如果该文章对您产生了帮助,麻烦动手点赞支持一下。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值