简体   繁体   中英

How to add a value to a specific line in a file in python?

I've seen really complex answers on this website as how to edit a specific line on a file but I was wondering if there was a simple way to do it? I want to search for a name in a file, and on the line that I find that name on, I want to add an integer to the end of the line (as it is a score for a quiz). Or could you tell me how I can replace the entirety of the line with new data? I have tried a lot of coding but either no change is made, or all of the data in the file gets deleted. I tried this....

with open ('File.py', 'r') as class_file:
        for number, line in enumerate(class_file):
            if name in line:
                s=open('File.py', 'r').readlines()
                s[number]=str(data)
                class_file=open('File.py', 'w')
                class_file.writelines(new_score)
                class_file.close()

As well as this function....

def replace (file, line_number, add_score):
    s=open(file, 'w')
    new_data=line[line_number].replace(line, add_score)
    s.write(str(new_data))
    s.close()

As well as this...

def replace_score(file_name, line_num, text):
    new = open(file_name, 'r').readlines()
    new[line_num] = text
    adding_score= open(file_name, 'w')
    adding_score.writelines(new)
    adding_score.close()

But I still can't get it to work. The last code works if I'm trying to replace the first line, but not the others.

You need to get the content of the file. Close the file. Modify the content and rewrite the file with the modified content. Try the following:

def replace_score(file_name, line_num, text):
  f = open(file_name, 'r')
  contents = f.readlines()
  f.close()

  contents[line_num] = text+"\n"

  f = open(file_name, "w")
  contents = "".join(contents)
  f.write(contents)
  f.close()

replace_score("file_path", 10, "replacing_text")

This is Tim Osadchiy's code:

def replace_score(file_name, line_num, text):
     f = open(file_name, 'r')
     contents = f.readlines()
     f.close()

     contents[line_num] = text+"\n"

     f = open(file_name, "w")
     contents = "".join(contents)
     f.write(contents)
     f.close()

replace_score("file_path", 10, "replacing_text")

This code does work but just remember that the line_num will always be one above the actual line number (as it is an index). So if you wanted line 9 then enter 8, not 9. Also, do not forget to put .txt at the end of the file path (I would've commented but do not have a high enough reputation)

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