Noob在这里。我需要使用read(而不是readlines())方法(为多个函数提供输入)读取文件,并标识该文件中的所有行(即打印或追加到列表中)。
我尝试了加入,拆分,追加到列表中,而几乎没有显示。
# Code I'm stuck with:
with open("text.txt", 'r') as file:
a = file.read()
# Stuff that doesn't work
for line in a:
# can't manipulate when using the below, but prints fine
# print(line, end = '')
temp = (line, end = '')
for line in a:
temp = ''
while not ' ':
temp += line
new = []
for i in a:
i = i.strip()
我倾向于将所有内容都放在长字符串中,或者 'I',',','t','e','n','d',','t','o'....获得单个字符。我只是想让每一行都达到换行符\ n,或者基本上是,尽管文件使用read()存储在内存中,但readlines()会给我什么?
答案 0 :(得分:3)
with open('text.txt') as file:
for line in file:
# do whatever you want with the line
file
对象可在文件的所有行上进行迭代-对于文本文件。
答案 1 :(得分:1)
您需要做的就是阅读后拆分文件,然后获得每一行的列表。
with open("text.txt", 'r') as file:
a = file.read()
a.split('\n')
答案 2 :(得分:0)
有了上述帮助,并使用读取行而不是读取行,我能够按如下所示从文件中分离出单独的行:
with open("fewwords.txt", "r") as file:
a = file.read()
empty_list = []
# break a, which is read in as 1 really big string, into lines, then remove newline char
a = a.split('\n')
for i in range(len(a)):
initial_list.append(a[i])