Python文件章节的一点题
内容不大,使用read()等方法将文件中所有字符都读出来进行比较是比较合适的;若文件内容较大,为了节省存储,可以每次读出一行字符进行比较,直到读出内容不相等或文件结束为止。请写出两种方式。
#方案1
with open("a.txt") as fpl:
fpl_content = fpl.read()
with open("b.txt")as fp2:
fp2_content =fp2.read()
if fpl_content == fp2_content:
print("no difference")
else:
print("differs")
#方案2
fp1 = open("a.txt")
fp2 = open("b.txt")
count =0
while True:
line_a = fpl.readline()
line_b = fp2.readline()
count += 1
if not line_a and not line_b:
if line_a != line_b:
print("line "+str(count)+" is difference")
break
else:
print("no difference")
fp1.close()
fp2.close()
2. 通讯簿文件(请自行创建文件)中存有若干个联系人的信息,每个联系人的信息由姓名和电话号码组成如下:
Zhang,2301
Zhao,2302
Li,2304
Sun,2305
编写程序完成以下功能:输入姓名,若通讯簿文件中存在则将该联系人信息输出,若不存在则输出“Not found”。
def find_contact(name):
with open("address_book.txt", "r") as f:
for line in f:
contact_name, phone = line.strip().split(',')
if contact_name == name:
return f"{contact_name},{phone}"
return "Not found"
name = input("请输入姓名:")
result = find_contact(name)
print(result)
3. 读出文件“file1.txt”(请自行创建文件)中的字符串,采用行程长度压缩编码方法RLC(根据测试数据理解此算法并自定义函数RLC实现此算法)进行压缩,并将结果写入“file2.txt”中。
测试数据:
“file1.txt”中的字符串:aaaaabbbbcccddddaafff
运行结果:
“file2.txt”中的字符串:a5b4c3d4a2f3
def rlc_encode(s):
result = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result += s[i - 1] + str(count)
count = 1
result += s[-1] + str(count)
return result
with open("file1.txt", "r") as f1:
content = f1.read()
compressed_content = rlc_encode(content)
with open("file2.txt", "w") as f2:
f2.write(compressed_content)
4. 创建一个文件Blowing in the wind.txt,其内容(复制粘贴就可以)是:
How many roads must a man walk down
Before you can call him a man
How many seas must a white dove sai
Before she sleeps in the sand
How many times must the cannon balls fly
Before they're forever banned
The answer my friend is blowing in the wind
The answer is blowing in the wind
- 根据以下要求编写程序
⑴在文件头部插入歌名“Blowin'in the wind”
⑵在歌名后插入歌手名“Bob Dylan”
⑶在文件末尾加上字符串“1962 by Warner Bros. Inc.”
⑷在屏幕上打印文件内容
文件处理后的内容为:
Blowin'in the wind
Bob Dylan
How many roads must a man walk down
Before you can call him a man
How many seas must a white dove sail
Before she sleeps in the sand
How many times must the cannon balls fly
Before they're forever banned
The answer my friend is blowing in the wind
The answer is blowing in the wind
1962 by Warner Bros. Inc.
with open("Blowing in the wind.txt", "r") as f:
content = f.readlines()
content.insert(0, "Blowin'in the wind")
content.insert(1, "Bob Dylan")
content.append("1962 by Warner Bros. Inc.")
with open("Blowing in the wind.txt", "w") as f:
f.writelines(content)
with open("Blowing in the wind.txt", "r") as f:
print(f.read())
5. 产生若干(至少100)行含10个0-9的随机数字字符串(只包含数字)的数据保存至一个文本文件中,计算每一行的各位数字之和,并把该行所有数据之和添加在其后,中间用“->”分隔。
import random
n =int(input("Enter the line numbers:"))
with open('random. txt', 'w+') as fp:
for i in range(n):
for j in range(10):
fp.write(str(random.randint(0, 9)))
fp. write('\n')
fp.seek(0)
nums = fp.readlines()
lst = []
for line in nums:
line_sum = sum(map(int, list (line.strip())))
lst. append(line.strip()+'->'+str(line_sum)+'\n')
fp. seek(0)
fp. writelines(lst)
6. 编写程序,统计某一个目录下(请自行创建)所有文本文件(.txt文件)的行数并输出。
import os
def countlines(fp):
data = fp.readlines()
lens = len(data)
print(fp.name +'has'+ str(lens)+'lines')
if __name__ == '__main__':
files = os.listdir('data/')
for fname in files:
with open('data/'+fname) as fp:
if fname.endswith('.txt'):
countlines(fp)