简体   繁体   English

使Python在程序运行时重新读取文件

[英]Making Python reread a file while the program is running

I am having trouble writing code for this program: 我无法为此程序编写代码:

#opening a file

addressbook = open("h:/A453/Address Book/AddressBook1.txt","r+")

line = addressbook.readline()

searchdata = input("Please enter the surname you are looking for ")

if searchdata in line:
    print(line)

All of the above work but it only reads the bottom line of text in the file when I run it. 以上所有工作,但运行时它仅读取文件中文本的底行。 I have researched this on the web but have not found anything useful or understandable. 我已经在网络上对此进行了研究,但没有发现任何有用或可理解的内容。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

The problem is that, you are using .readline() which reads only one line from the file to read the whole file you have 2 options: .read() or .readlines() 问题是,您正在使用.readline()从文件中仅读取一行以读取整个文件,您有2个选项: .read().readlines()

.read() method It reads the contents of the file in one go and returns a string with all the escape characters and spaces preserved. .read()方法一次性读取文件的内容,并返回一个保留了所有转义字符和空格的字符串。

.readlines() It reads the file and returns a list of contents of the file whose elements are split() at each newline. .readlines()读取文件并返回文件内容的列表,其内容在每个换行符处都是split()

#opening a file

addressbook = open("h:/A453/Address Book/AddressBook1.txt","r+")

line = addressbook.read()

searchdata = input("Please enter the surname you are looking for ")

if searchdata in line:
    print(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM