如何在文件中查找单词或行并用新单词替换它下面的行?

时间:2017-03-03 04:50:29

标签: python-3.x replace find next

如果这看起来很无聊,我道歉但我找不到我想要做的事情。我制作了一个招标工作的程序,我希望使用一个文本文件作为配置文件来存储价格等,程序可以根据需要读取和写入。这是我的基本内容。

::示例代码::

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”下的行。我可以不做任何事情或者擦除文件而不是我想要的文件。

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

2 个答案:

答案 0 :(得分:0)

你可以这样做。

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()

答案 1 :(得分:0)

经过将近一周的时间,编写了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

我希望这很清楚,可以帮助别人。如果你有任何请纠正我或加入,总是有更好的办法做到这一点。