擅长:python、mysql、java
<p>给你,这个就行了。你知道吗</p>
<p>正如Mateen Ulhaq在评论中提到的那样,如果不重写整个文件,那么就没有合理的方法来实现这一点,所以这个解决方案只包含这一点。但是,只有在找到带有初始文件的choosen名称时,它才会重写文件。你知道吗</p>
<p>另外,当输入的数字不是一个真正的数字时,这也不能处理这种情况,所以如果有人输入<code>notnumber123</code>作为选择的数字,它仍然会被写入文件。你知道吗</p>
<pre><code>filepath = 'hei.txt'
choosen_name = input('Choose name: ')
choosen_num = input('Choose number: ')
with open(filepath) as f:
content = f.readlines()
file_changed = False
new_content = []
for line in content:
if choosen_name in line:
new_content.append('{} {}\n'.format(choosen_name, choosen_num))
file_changed = True
else:
new_content.append(line)
if file_changed:
with open(filepath,'w') as f:
for line in new_content:
f.write('{}'.format(line))
else:
print('Choosen name not found.')
</code></pre>