将文本文件读入字符串

2024-10-03 11:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习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

任何帮助都将不胜感激。你知道吗


Tags: 文件字符串inhelloworldif结尾数字
3条回答

读取文件后:

read_file = read_file.replace('hello','55hello55')

它会用55hello55替换所有的HELLO

使用with open(text.txt, 'r' ) as file_hndler:

您需要迭代文件的每一行以获得所需的结果。在代码中使用.read(),而不是使用.readlines()来获取所有行的列表。你知道吗

下面是示例代码:

lines = []
with open("test.txt", "r") as f:
     for line in f.readlines():  # < Iterate over each line
         if line.startswith("Hello"):  # <-- check if line starts with "Hello"
             line = "55{}55".format(line)
         elif line.startswith("World"):
             line = "66{}66".format(line)
         lines.append(line)

print "\n".join(lines)

为什么要使用with?检查Python doc

The ‘with‘ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with‘ statement is a control-flow structure whose basic structure is:

with expression [as variable]: with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods).

使用.read()一次读取整个文件。你知道吗

您可以在for循环中逐行读取它。你知道吗

new_file = []
fp = open("test.txt", "r")
for line in fp:
    line = line.rstrip("\n")  # The string ends in a newline
                              # str.rstrip("\n") removes newlines at the end
    if "Hello" in line:
        line = "55" + line + "55"
    if "World" in line:
        line = "66" + line + "66"
    new_file.append(line)
fp.close()
new_file = "\n".join(new_file)
print(new_file)

通过读取整个文件并按“\n”(换行符)拆分,可以一次完成所有操作

new_file = []
fp = open("text.txt")
fp_read = fp.read()
fp.close()
for line in fp_read.split("\n"):
    if "Hello" # ...

但这会一次将整个文件加载到内存中,而for循环只逐行加载(因此这可能不适用于较大的文件)。你知道吗

这样做的行为是,如果行中有“Hello”,那么它前后都会得到“55”(即使行是“sieohfoiHellosdf”),对于“World”也是一样的,如果它同时有“Hello”和“World”(例如,“Hello,World!”或者“asdifhoasdfhHellosdjfhsodWorldosadh”),它前后都会得到“6655”。你知道吗

作为旁注:您应该使用with打开一个文件,因为它可以确保稍后关闭该文件。你知道吗

new_file = []
with open("test.txt") as fp:  # "r" mode is default
    for line in fp:
        line = line.rstrip("\n")
        if "Hello" in line:
            line = "55" + line + "55"
        if "World" in line:
            line = "66" + line + "66"
        new_file.append(line)
new_file = "\n".join(new_file)
print(new_file)

相关问题 更多 >