简体   繁体   English

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

[英]how to read lines in python and then assign each line to a variable

I am trying to write a code that will take a file see those letters then take them and make them in to other letters.我正在尝试编写一个代码,该代码将获取一个文件,查看这些字母,然后将它们放入其他字母中。 hear is my code.听到是我的代码。

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

the output is output 是

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

>>>

ideas?想法?

You can get a list of lines with readlines() :您可以使用readlines()获取行列表:

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

You can also iterate through the lines of a file with a for loop:您还可以使用 for 循环遍历文件的行:

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

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

相关问题 如何从python中的重复文本模式为每一行分配一个变量? - how to assign a variable to each line from a repeating text pattern in python? 如何将多行代码分配给Python中的变量? - How to assign multiple lines of code to a variable in Python? 从文件中读取每一行并分配给循环中的变量 - read each line from a file and assign to a variable in a loop Python - 读取文本文件的每一行并将每一行传递给变量 - Python - Read each line of text file and pass each line to variable 如何逐行读取python中的txt文件并将每行设置为一个变量 - How to read txt file in python line by line and set each line to a variable 如何读取文本文件的每一行并将每一行转换为元组? - how to read each lines of a text file and convert each line to a tuple? Python读取csv文件,将每一行赋值给一个变量 - Python reading csv files, assign each line to a variable 如何在同一行上取两个字符串并在 python 中为每个字符串分配一个变量? - How can I take two strings on the same line and assign each of them a variable in python? 如何循环和索引 python 中的文件内容并将每一行分配给不同的变量 - How to loop and index through file content in python and assign each line for different variable 如何将一行 python 代码分配给变量 - How to assign a line of python code to a variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM