使用Python更改文件中的文本

使用Python更改文件中的文本,python,python-3.x,Python,Python 3.x,对于我输入的用户名,我不会将单词False更改为True 我在文件用户中有此文本: def false_to_true(): name = input("Input name: ") file=open("users.txt","r") lines = file.readlines() file.close() for line in lines: username, lel, type = line.split("/")

对于我输入的用户名,我不会将单词False更改为True

我在文件用户中有此文本:

def false_to_true():
    name = input("Input name: ")
    file=open("users.txt","r")
    lines = file.readlines()
    file.close()
    for line in lines:
        username, lel, type = line.split("/")
        while name == username:
            name = input("input name again: ")
    tip = True
    with open("users.txt", "w") as users:
        users.write(str(red))

#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False

您只需使用csv库,就可以忘记字符串操作:

Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False

询问用户名并反复抛出行以检查用户名,如下所示:

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

打开输入和输出文件,设置以空行结尾的用户输入名称,然后为检查用户输入名称成员资格的正确格式字符串创建生成器,然后将这些行写入输出文件:

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

要在位修改文本文件,您可以:


请参见

您的代码删除文件中的所有行并输入文件中的最后一行代码?我的文件中没有仅用于注释@Zetys的代码
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)
#!/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='')