前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之路-day4

Python之路-day4

作者头像
企鹅号小编
发布2018-01-25 15:15:09
5250
发布2018-01-25 15:15:09
举报
文章被收录于专栏:编程编程

#读取文件内容

withopen("readme.txt")asmyFile:

content = myFile.readlines()

print(content)

#把内容写入文件

withopen("hello.txt","w")asmyFile:

myFile.write("hello world!\n")

这是一段读取文件和写入文件的代码,参考书是:《Head First Head》

要注意的是以下几点:

此段代码文件保存位置是:C:/Users/苏小爪/20171208.py

所以“readme.txt”和“hello.txt”需要存放在同一位置

书中案例,将一个类似剧本的人物对话内容文件(sketch.txt),按照人物角色进行分类,要实现拆分为两个文件(man_data.txt 和 other_data.txt)

问题分析:

每一行第一个“:”后面是对应人物的说话内容;

有些行不止一个“:”;

分两个列表存储对话内容,Man 和 Other;

新建两个文件,将列表内容写入;

#台词分类程序

man = []

other = []

try:

data =open('sketch.txt')

foreach_lineindata:

try:

(role,line_spoken) = each_line.split(':',1)

line_spoken = line_spoken.strip()

ifrole =='Man':

man.append(line_spoken)

elifrole =='Other Man':

other.append(line_spoken)

exceptValueError:

pass

data.close()

exceptIOError:

print('The data file is missing!')

try:

man_file =open('man_data.txt','w')

other_file =open('other_data.txt','w')

print(man,file=man_file)

print(other,file=other_file)

man_file.close()

other_file.close()

exceptIOError:

print('File error.')

输出:

数据处理练习:

如果list中既包含字符串,又包含整数,由于非字符串类型没有方法,所以列表生成式会报错,现在通过使用内建的函数可以判断一个变量是不是字符串,使用if语句,生成列表L2,列表内容为处理后的小写字符串。

# -*- coding: utf-8 -*-

L1 = ['Hello','World',18,'Apple',None]

L2 = []

forxinL1:

ifisinstance(x,str):

L2.append(x)

else:

pass

print(L2)

print([s.lower()forsinL2])

输出:

['Hello', 'World', 'Apple']

['hello', 'world', 'apple']

本文来自企鹅号 - 终身学习者的自习室媒体

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

本文来自企鹅号 - 终身学习者的自习室媒体

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档