Cats萌萌
尝试这个。如果它满足第一个要求但不满足另一个要求,则您没有其他情况。ans = 'test'numdef = ['H',2] f = open(textfile, 'r')lines = f.readlines()f.close()f = open(textfile, 'w')f.write('')f.close()f = open(textfile, 'a')for line in lines: if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]: k = line.replace('\n','')+ans f.write(k) else: f.write(line)f.close()更好的方法:#initialize variablesans = 'test' numdef = ['H',2] #open file in read mode, add lines into lineswith open(textfile, 'r') as f: lines=f.readlines() #open file in write mode, override everything with open(textfile, 'w') as f: #in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file. f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))