Task9: 文件与文件系统
练习题:
1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
- 使用
open(path, 'r', encoding = 'utf-8')
语句来打开中文字符文档
2、编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
with open(filename, 'r', encoding = 'utf-8') as f:
data = f.read().strip().split('\n')
data1 = ' '.join(data).split(' ')
data1.sort(key = lambda x:len(x))
longest = [i for i in data1 if len(i) == len(data1[-1])]
return longest