我刚刚开始学习python,有一个文本文件如下所示:
Hello
World
Hello
World
我想把数字“55”加到以“hello”开头的每个字符串的开头和结尾
数字“66”到begging和以“World”开头的每个字符串
等等
所以我的最终文件应该是这样的:
55Hello55
66World66
55Hello55
66World66
我一次读取所有文件,将其存储在字符串中,然后尝试相应地追加
fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)
if 'Hello' in strHolder:
strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
但是,我的字符串值“55”和“66”总是被添加到文件的前面和结尾,而不是某个字符串的前面和结尾,在这里我得到了这个字符串的输出:
6655Hello
World
Hello
World
5566
任何帮助都将不胜感激。你知道吗
读取文件后:
它会用55hello55替换所有的HELLO
使用
with open(text.txt, 'r' ) as file_hndler:
您需要迭代文件的每一行以获得所需的结果。在代码中使用
.read()
,而不是使用.readlines()
来获取所有行的列表。你知道吗下面是示例代码:
为什么要使用
with
?检查Python doc:使用
.read()
一次读取整个文件。你知道吗您可以在
for
循环中逐行读取它。你知道吗通过读取整个文件并按“\n”(换行符)拆分,可以一次完成所有操作
但这会一次将整个文件加载到内存中,而for循环只逐行加载(因此这可能不适用于较大的文件)。你知道吗
这样做的行为是,如果行中有“Hello”,那么它前后都会得到“55”(即使行是“sieohfoiHellosdf”),对于“World”也是一样的,如果它同时有“Hello”和“World”(例如,“Hello,World!”或者“asdifhoasdfhHellosdjfhsodWorldosadh”),它前后都会得到“6655”。你知道吗
作为旁注:您应该使用
with
打开一个文件,因为它可以确保稍后关闭该文件。你知道吗相关问题 更多 >
编程相关推荐