简体   繁体   中英

How to find a word or line in file and replace the line under it with a new word?

I apologize if this seems noobish but I can't find exactly what I'm trying to do. I made a program for bidding jobs and I want to use a text file as a config file to store pricing etc which the program can read and write to as needed. Here is a basic of what I have.

::Example Code::

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

:: Example JobFiles.txt::

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

::Example of Intended file::

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

So it should read the file "JobFiles.txt" and replace the line under "Flooring Price" with the user input. I can get it to do nothing or wipe the file but not what I intend.

edit: It should search the text file for a word ie "Flooring Price" and replace the line under it, that way the file can grow and change with out having to re code to adjust for whether "Flooring Price" is on line 1 or line 100.

You can do something like this.

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

After nearly a week and 3357 lines of code written I've completed my program! So here is how to do what I was trying to figure out, Search a file for a line and replace the line under it.

::For finding info::

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

::For changing file::

 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

I hope this is clear and can help others. There's always better ways to do things so by all means if you have any please correct me or add to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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