![](/img/trans.png)
[英]How to read the string from an .INI file and then read that string from a text file and print the entire line using Python?
[英]Python 2: How do I search for a string in a text file before returning the entire line from the text file that contains this string?
用例:用戶輸入一個ID碼。 存儲的文件包含有關人員的信息,每人一行,包括其ID碼。 我需要在文件中找到該用戶的行,並將其附加到另一個文本文件中。
with open("file.txt") as file:
for line in file:
if id_code in line:
yield line
怎么辦? 我如何從產生該行到將其保存到另一個文件中? 另外,如果文件中根本沒有ID碼,我可以要求他們重試嗎?
如果沒有實際的txt文件,很難說這是否可以完美地工作,但這是正確的總體思路。
with open("file.txt", "r") as f, open("otherfile.txt", "a") as g:
for line in file.readlines():
lineparts = line.split()
if id_code in lineparts:
g.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.