Change text in file with Python

前端 未结 4 509
忘了有多久
忘了有多久 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: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()
    

提交回复
热议问题