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

时间:2015-05-14 11:34:39

标签: python

我在编写此程序的代码时遇到问题:

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

以上所有工作,但它只在我运行时读取文件的底线。我在网上研究了这个,但没有找到任何有用或可理解的东西。任何帮助,将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

问题在于,您使用.readline()只从文件中读取一行来读取整个文件,您有两个选项:.read().readlines()

.read()方法 它一次读取文件的内容并返回一个字符串,其中保留了所有转义字符和空格。

<强> .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)
相关问题