1.5 python文件操作

    技术2025-12-24  15

    1.5 python文件操作

    1.5.1 文件的具体操作打开文件写数据(write)读数据(read)part 1part 2 总结打开文件文件操作方法 1.5.2 操作实例

    1.5.1 文件的具体操作

    打开文件

    f = open('test.txt', 'w')

    在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件: open(文件名,访问模式)

    写数据(write)

    f = open('test.txt', 'w') f.write('hello world,\n') f.write('i am here!\n') f.close()

    结果

    hello world, i am here!

    读数据(read)

    part 1

    f = open('test.txt', 'r') content = f.read(5) print(content) print("-"*30) content = f.read() print(content) f.close()

    结果

    hello ------------------------------ world, i am here!

    使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

    part 2

    f = open('test.txt', 'r') content = f.readlines() print(type(content))

    结果

    ['hello world,\n', 'i am here!\n'] <class 'list'>

    总结

    打开文件

    文件操作方法

    1.5.2 操作实例

    小说《Walden》单词词频统计 Walden中文译名《瓦尔登湖》,是美国作家梭罗独居瓦尔登湖畔的记录,描绘了他两年多时间里的所见、所闻和所思。该书崇尚简朴生活,热爱大自然的风光,内容丰厚,意义深远,语言生动。请用Python统计小说Walden中各单词出现的频次,并按频次由高到低排序。 示例: lyric = ‘The night begin to shine, the night begin to shine’ words = lyric.split() print(words) words.count(words[1])

    import re # 正则表达式 f = open('Walden.txt', 'r') txt = f.read() # 读取进来的数据类型是字符串 f.close() txt = txt.lower() # 英文字母全部变成小写 txt = re.sub('[,.?:"\'!-]', '', txt) # 去除小说中的标点符号 words = txt.split() # 单词分割 word_sq = {} for i in words: if i not in word_sq.keys(): word_sq[i] = 1 else: word_sq[i] += 1 res = sorted(word_sq.items(), key=lambda x:x[1], reverse=True) # 排序 print(res)

    txt = re.sub('[,.?:"\'!-]', '', txt) txt = re.sub('带去除的内容', '需替换的内容',需处理的字符串) res = sorted(word_sq.items(), key=lambda x:x[1], reverse=True) reverse是降序排列

    结果太长了,自己运行

    附 'Walden.txt', 字数限制,需要的私聊我

    Processed: 0.015, SQL: 9