简体   繁体   English

如何使用 Python 修改文件中的一行

[英]How to modify a line in a file using Python

I am trying to do what for many will be a very straight forward thing but for me is just infuriatingly difficult.我正在努力做对许多人来说是一件非常直接的事情,但对我来说却是非常困难。 I am trying search for a line in a file that contains certain words or phrases and modify that line...that's it.我正在尝试在包含某些单词或短语的文件中搜索一行并修改该行……就是这样。 I have been through the forum and suggested similar questions and have found many hints but none do just quite what I want or are beyond my current ability to grasp.我已经浏览了论坛并提出了类似的问题,并找到了许多提示,但没有一个完全符合我的要求,或者超出了我目前的掌握能力。

This is the test file:这是测试文件:

# 1st_word  2nd_word

# 3rd_word  4th_word

And this is my script so far:到目前为止,这是我的脚本:

############################################################
file = 'C:\lpthw\\text'
f1 = open(file, "r+")
f2 = open(file, "r+")
############################################################

def wrline():
    lines = f1.readlines()
    for line in lines:
        if "1st_word" in line and "2nd_word" in line:
            #f2.write(line.replace('#\t', '\t'))
            f2.write((line.replace('#\t', '\t')).rstrip())
    f1.seek(0)

wrline()

My problem is that the below inserts a \n after the line every time and adds a blank line to the file.我的问题是,下面每次都会在该行之后插入一个 \n 并在文件中添加一个空行。

f2.write(line.replace('#\t', '\t'))

The file becomes:文件变为:

    1st_word    2nd_word


#   3rd_word    4th_word

An extra blank line between the lines of text.文本行之间的额外空白行。

If I use the following:如果我使用以下内容:

f2.write((line.replace('#\t', '\t')).rstrip())

I get this:我明白了:

    1st_word    2nd_wordd

#   3rd_word    4th_word

No new blank line inserted but and extra "d" at the end instead.没有插入新的空白行,而是在末尾添加了额外的“d”。

What am I doing wrong?我究竟做错了什么?

Thanks谢谢

I would keep read and write operations separate.我会将读写操作分开。

#read
with open(file, 'r') as f:
    lines = f.readlines()

#parse, change and write back
with open(file, 'w') as f:
    for line in lines:
        if line.startswith('#\t'):
            line = line[1:]
    f.write(line)

Your blank line is coming from the original blank line in the file.您的空白行来自文件中的原始空白行。 Writing a line with nothing in it writes a newline to the file.写一个没有任何内容的行会在文件中写入一个换行符。 Instead of not putting anything into the written line, you have to completely skip the iteration, so it does not write that newline.您必须完全跳过迭代,而不是不将任何内容放入写入的行中,因此它不会写入该换行符。 Here's what I suggest:这是我的建议:

def wrline():
    lines = open('file.txt', 'r').readlines()
    f2 = open('file.txt', 'w')
    for line in lines:
        if '1st_word' in line and '2nd_word' in line:
            f2.write((line.replace('# ', ' ')).rstrip('\n'))
        else:
            if line != '\n':
                f2.write(line)
    f2.close()

You have not closed the files and there is no need for the \t您还没有关闭文件,也不需要\t

Also get rid of the rstrip()也摆脱rstrip()

Read in the file, replace the data and write it back.. open and close each time.读入文件,替换数据并将其写回..每次打开和关闭。

fn = 'example.txt'
new_data = []

# Read in the file
with open(fn, 'r+') as file:
    filedata = file.readlines()

# Replace the target string
for line in filedata:
    if "1st_word" in line and "2nd_word" in line:
        line = line.replace('#', '')
    new_data.append(line)

# Write the file out again
with open(fn, 'w+') as file:
    for line in new_data:
        file.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM