这是一个非常低级的问题,但我只是尝试将数据(作为单独的元素)输入到文件中,然后将它们作为单独的元素检索到列表中,而不是作为一个大字符串。
到目前为止,我所做的就是将数据保存到一个文件中,当我去检索它时,它会以一个大字符串的形式出现(没有\t或\n或任何我可以用来拼接的字符串)。Python3对于绝对的初学者和谷歌搜索还没有帮助我解决这个问题。我在这个网站上搜索没有得到任何我能理解的东西。
任何帮助都将不胜感激。
发布于 2020-04-04 21:01:51
尝试使用下面的代码来读写文本文件
# For writing to a text file
f= open("demo.txt","w+")
for i in range(5):
f.write("This is line {}\n".format(i+1))
f.close()
# For reading a text file and store the lines to a list
f=open("demo.txt", "r")
if f.mode == 'r':
ls = []
ch = ""
contents =f.read()
for i in contents:
if i != "\n":
ch += i
else:
ls.append(ch)
ch = ""
print(ls)注意:当向文件中写入一行时,请确保在末尾使用\n来表示新行。
https://stackoverflow.com/questions/61028321
复制相似问题