如何在python中读取行然后将每一行分配给一个变量

时间:2021-01-03 16:38:54

标签: python

我正在尝试编写一个代码,该代码可以让文件看到这些字母,然后将它们转换为其他字母。听到的是我的代码。

def decode():
    dd=input("would you like to type the message or read a file that has the message?:")
    if dd in['read']:
        e=open("file.txt", 'r')
        for i in range(7):
            ff=e.read()
            if ff in['wen']:
                print("new")
             ...
        e.close()
decode()

输出是

would you like to type the message or read a file that has the message?: read

>>>

想法?

1 个答案:

答案 0 :(得分:0)

您可以使用 readlines() 获取行列表:

e = open("file.txt", 'r')
lines = e.readlines()
e.close()

您还可以使用 for 循环遍历文件的行:

e = open("file.txt", 'r')
for line in e:
     #your code here
e.close()
相关问题