Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何编写一个可以读取文本文件并写入列表的函数?_Python_List_Readfile - Fatal编程技术网

Python 如何编写一个可以读取文本文件并写入列表的函数?

Python 如何编写一个可以读取文本文件并写入列表的函数?,python,list,readfile,Python,List,Readfile,如何编写可以读取文本文件并将其附加到列表中的函数 先谢谢你。 我试过了,但没用 def readdata (z): x=[ ] for dig in open(z).readlines(): digx=dig.strip().split(" ") if len(dig) == 0: print return 0 else : return x.append(str(digx)) print x read

如何编写可以读取文本文件并将其附加到列表中的函数 先谢谢你。 我试过了,但没用

def readdata (z):
x=[ ]
for dig in open(z).readlines():
    digx=dig.strip().split(" ")
    if len(dig) == 0:
        print 
        return 0

    else :
        return x.append(str(digx))
        print x
 readdata (r'C:\Users\Administrator\Coding\Python\Text\Day5\scores.txt')

这是Python中的两行程序

with open("myfile.txt") as file:
    lines = file.readlines()

是文件行的列表。每个字符都将以'\n'(换行符)结尾,最后一行可能除外。

我猜是在汇编中。您希望列表中有什么内容?每行一个列表条目?什么类型的列表?我怀疑我读的“并且不调用其他函数或代码”是对的,因为这意味着你希望它神奇地发生。在编程中没有什么神奇的事情发生。反对票反映了这样一个事实:在StackExchange上发布问题之前,你应该做一些基础研究。阅读常见问题解答,欢迎来到社区!另外,还有一个非常好的技巧(如果我自己这么说的话!)在脚本的开头使用pdb.set_trace()并仔细阅读。您必须在开始时导入pdb。你可以在线阅读有关pdb或其更直观的同类产品,如pudb、winpdb等。为什么不干脆
lines=list(file)
呢?如果你只是想把它存储在内存中,那就不太需要generator@JoranBeasley符合事实的我只是习惯于使用生成器,因为我很少存储中间结果。但是是的,对于OP的问题,你的建议更简洁。