python 文件读取写入

文章内容不再更新,因为内容已经写入Gitee仓库,只在仓库更新

地址

3.1415926535
8979323846
2643383279

文件

读文件

文件的内容读取到内存   解读为字符串    如果是数值要计算的话   int()  float()

# 读取整个文件
filename = "D:\demo.js"
# with open(filename) as file_object:
#     contents = file_object.read()
#     print(contents.rstrip())


#逐行读取
# with open(filename) as file_object:
#     for line in file_object:
#        print(line.rstrip())



# readline()  从文件中读取每一个字,并将其存储在一个列表中  然后存在lines
# readlines() 从文件中读取每一行,并将其存储在一个列表中  然后存在lines
with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())
with open('re.txt','r',encoding='utf-8') as file_object:
    contents = file_object.read()   #有readline()
    print(contents)


#utf-8格式打开文档
f = open(r're.txt','r',encoding='utf-8')
f.seek(0,0)                    # 重新设置文件读取指针到开头
for each_line in f:            # 逐行读取
    print(each_line.rstrip())  # rstrip  删除多余空白行
f.close()


#以二进制打开文件,然后对读取的内容进行utf-8编码
f = open(r're.txt','rb')
f.seek(0,0)
for each_line in f:
    print(each_line.decode('utf-8'))
f.close()

#查看圆周率中包含自己生日吗?
with open('pi_million_digits.txt') as file_object:
    lines = file_object.readline()
    pi_string = ""
    for line in lines:
        pi_string += line.strip()

birthday = input("Enter you birthday :")    # 970104
if birthday in pi_string:
    print('yes')
else:print('not')

filename = 're.txt'

with open(filename, 'a') as file_object:    #附加 a   单纯的覆盖 w
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

name = input("What's your name? ")
with open(filename, 'a') as f:
    f.write(name)

计算一个文件大致有多少个单词


def count_words(filename):
    """Count the approximate number of words in a file."""
    try:
        with open(filename,encoding='utf-8') as f_obj:
            contents = f_obj.read() 
    except FileNotFoundError:
        pass
    else:
        # Count approximate number of words in the file.
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

filenames = ['re.txt','pi_million_digits.txt']  #,'pi_million_digits.txt'
for filename in filenames:
    count_words(filename)

The file re.txt has about 21 words.
The file pi_million_digits.txt has about 10000 words.

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

huang_ftpjh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值