【问题标题】:How to find a word or line in file and replace the line under it with a new word?如何在文件中查找单词或行并将其下的行替换为新单词?
【发布时间】:2017-07-23 02:12:32
【问题描述】:

如果这看起来很无聊,我深表歉意,但我无法准确找到我想要做的事情。我制作了一个用于投标工作的程序,我想使用一个文本文件作为配置文件来存储定价等,程序可以根据需要对其进行读写。这是我所拥有的基本知识。

::示例代码::

def job():
    question1 = input("Do you want to adjust your pricing? ").lower()
    if question1 == "y" or question1 == "yes":
        question2 = input("\nWhat price point would you like to change?\nFlooring cost(1), Basic repair cost(2), or Fuel mileage cost(3): ")
        if question2 == "1":
            flooring_cost = input("\nWhat is your charge per sqft for flooring? ")
            with open("JobFiles.txt", "r") as fo, open("JobFiles.txt", "a") as fw:
                for line in fo:
                    if line == "Floor Price":
                        next(fo)
                        fw.write(flooring_cost + "\n")
                fo.close()
                fw.close()
            return job()

:: 示例 JobFiles.txt::

Flooring Price
2.50    <----------<<
Basic Repair Price
25
Fuel Charge
0.40

::预期文件示例::

Flooring Price
2.75    <----------<<
Basic Repair Price
25
Fuel Charge
0.40

所以它应该读取文件“JobFiles.txt”并将“Flooring Price”下的行替换为用户输入。我可以让它什么都不做或擦除文件,但不是我想要的。

编辑:它应该在文本文件中搜索一个词,即“Flooring Price”并替换它下面的行,这样文件就可以增长和更改,而无需重新编码来调整“Flooring Price”是否打开第 1 行或第 100 行。

【问题讨论】:

  • 我的解决方案完全符合您的要求,只是打印了一个额外的新行。不正确?
  • @WasiAhmad 是的先生,您的解决方案适用于本示例,只是它删除了 0.40 并留下一个空行。
  • 不,它工作得很好,我已经检查过了。查看我的代码,我没有删除从文件中读取的任何行。仔细研究我的代码,希望你会明白。

标签: python-3.x replace find next


【解决方案1】:

经过将近一周和 3357 行代码的编写,我已经完成了我的程序!所以这里是如何做我想弄清楚的,在文件中搜索一行并替换它下面的行。

::查找信息::

with open("test_folder/test", "r") as fo:#<---<< opens the file in read mode
    data = fo.readlines()#<---<< saves the file to a list variable
for i, line enumerate(data):#<---<< gets the line numbers
    if "key word" in line:#<---<< searches for key word
        n = i + 1#<---<< takes the line number from the key word and adds one aka moves down one line
        var = data[n].strip()#<---<< adds line from file to a variable and removes the /n

::换文件::

 with open("test_folder/test", "r") as fo:  #<---<<
    data = fo.readlines()                   #<---<<
for i, line enumerate(data):                #<---<<
    if "key word" in line:                  #<---<<
        n = i + 1                           #<---<<
data[n] = "%s\n" % (var2)#<---<< changes the value on the line in the list
with open("test_folder/test", "w") as fw:#<---<< opens file in write mode
    fw.writelines(data)<---<< writes the altered list back to file

我希望这很清楚并且可以帮助其他人。总是有更好的方法来做事,所以如果你有任何方法,请纠正我或补充。

【讨论】:

    【解决方案2】:

    你可以这样做。

    def job(value):
        question1 = input("Do you want to adjust your pricing? ")
        question1 = question1.lower()
        if question1[0] == "y" or question1 == "yes":
            question2 = input("\nWhat price point would you like to change?\nFlooring cost(1),"
                              "Basic repair cost(2), or Fuel mileage cost(3): ")
            if question2 == "1":
                flooring_cost = input("\nWhat is your charge per sqft for flooring? ")
                value[0] = flooring_cost
        return value
    
    filename = "JobFiles.txt"
    f = open(filename, 'r')
    key = []
    value = []
    while True:
        line1 = f.readline().rstrip() # reading odd no. line
        line2 = f.readline().rstrip() # reading even no. line
        if not line2:
            break
        else:
            key.append(line1) # every odd no. line is the key, ex. Flooring Price
            value.append(line2) # every even no. line is the value, ex. 2.50
    f.close()
    
    value = job(value)
    fo = open(filename, 'w')
    for key, value in zip(key, value):
        fo.write(key + '\n' + value + '\n') # writing pairs of line in file
    fo.close()
    

    【讨论】:

    • 非常感谢您的宝贵时间!我尝试了您的代码,虽然它确实将值写入文件,但它不会替换所需行下的行,而是用输入替换第二行并删除文件中的最后一行。
    • @FurikuriYugi 删除最后一行?你能在你的帖子中解释你对输出的期望吗?因为我已经检查过了。你在文件中有多少行? 6,对吧?看我的代码。没有任何错误!你发现那里有什么错误的逻辑吗?
    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 2011-04-25
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2023-03-31
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多