17.文件与文件系统
strip()
方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列(不能删除中)
1.文件与文件系统
2.OS 模块中关于文件/目录常用的函数
- 在设置路径时在字符串前加"r"代表处理不转义对象,详细情况见Task04字符串相关内容
- 浮点型秒数,可用time模块的
gmtime()
或localtime()
函数换算
练习
-
打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
-
编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
# your code here
pass
def longest_word(filename):
#看题目中输出的最后有个逗号,所以说明单词是以逗号隔开
f = open(filename, 'r')
lines = f.readlines() # 把某一行的全部当作一个字符串,作为列表中的一个元素
max = []
danci = ''
l_max = 0
for i in lines:
while len(i) > 0:
flag = i.find(',')
danci = i[0:flag + 1]
l = len(danci)
if l > l_max:
if len(max) == 0:
max.append(danci)
elif len(max) != 0 :
max.append(danci)
max.pop(0)
l_max = l
elif l == l_max:
max.append(danci)
i = i[flag + 1:]
return max
print(longest_word('text.txt'))