从文件中提取一行,并按lin的开头进行更改

2024-04-19 21:09:39 发布

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

所以我想在文件中查找一些东西,当我读到一行以#开头的时候,我想在这行的前面和结尾打印一些东西

file = open("something.py","r")
infile = file.readlines()

for line in infile:
    if line.find("#") !=-1:
        index = line.find("#")
        print("BLABLABLA",the line that begins with #,"BLABLABLA", end="")

Tags: 文件inpyforindexif结尾line
2条回答

简单(&A);很短。最后两行将根据您的标志和您想对读取的行实际执行的操作而改变

with open('input.txt', 'r') as f:
    for line in f:
        if line.startswith('#'):
            print('!!!' + line.strip() + '!!!')

这个怎么样:

# Open file for reading
with open("infile.txt", "r") as infile:
    # Open another file for writing
    with open("outfile.txt", "w") as outfile:
        # Read each line from the input file
        for line in infile.readlines():
            # Check if line begins with keyword "Hello"
            if line.startswith("Hello"):
                # If it does, prepend and append something to the line
                line = "Prepend! >>> " + line.strip() + " <<< Append!"
            # Finally, write the line to outfile
            outfile.write(line + "\n")

输入:

Hello, this is a line.
Hello, this is another line.
Goodbye, these were all the lines

输出:

Prepend! >>> Hello, this is a line. <<< Append!
Prepend! >>> Hello, this is another line. <<< Append!
Goodbye, these were all the lines

相关问题 更多 >