Change text in file with Python

前端 未结 4 497
忘了有多久
忘了有多久 2020-12-22 14:17
def false_to_true():
    name = input(\"Input name: \")
    file=open(\"users.txt\",\"r\")
    lines = file.readlines()
    file.close()
    for line in lines:
              


        
相关标签:
4条回答
  • 2020-12-22 14:31

    Ask for name and iterate throw your lines to check for username, like this:

    def false_to_true():
        name = input("Input name: ")
        file=open("users.txt","r")
        lines = file.readlines()
        file.close()
    
        users = open("users.txt", "w")
        for line in lines:
        username, lel, type = line.split("/")
        if name == username:
            type = 'True\n'# \n for new line type ends with '\n'
        users.write("/".join([username, lel, type]))
        users.close()
    false_to_true()
    
    0 讨论(0)
  • 2020-12-22 14:37

    You can just use the csv library and forget about string manipulation:

    import csv
    
    def false_to_true():
        #read from user.txt file into list(data)
        with open('users.txt', 'r') as userfile:
            data = [row for row in csv.reader(userfile,
                                              delimiter="/",
                                              quoting=csv.QUOTE_NONE)]
        while True:
            #waiting for input until you enter nothing and hit return
            username = input("input name: ")
            if len(username) == 0:
                break
            #look for match in the data list
            for row in data:
                if username in row:
                    #change false to true
                    row[2] = True
                    #assuming each username is uniqe break out this for loop
                    break
    
        #write all the changes back to user.txt
        with open('users.txt', 'w', newline='\n') as userfile:
            dataWriter = csv.writer(userfile,
                                    delimiter="/",
                                    quoting=csv.QUOTE_NONE)
            for row in data:
                dataWriter.writerow(row)
    
    
    if __name__ == '__main__':
        false_to_true()
    
    0 讨论(0)
  • 2020-12-22 14:50

    To modify a text file inplace, you could use fileinput module:

    #!/usr/bin/env python3
    import fileinput
    
    username = input('Enter username: ').strip()
    with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
        for line in file:
            if line.startswith(username + "/"):            
                line = line.replace("/False", "/True") 
            print(line, end='')
    

    See How to search and replace text in a file using Python?

    0 讨论(0)
  • 2020-12-22 14:57

    Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:

    with open('names.txt') as f, open('result.txt', 'w') as out:
        names = {name for name in iter(input, '')}
        f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
        output.writelines(f)
    
    0 讨论(0)
提交回复
热议问题