Skip to main content
 首页 » 编程设计

python之从文件中读取会删除文档中最后一个字符串的最后一个字母

2025年05月04日43cmt

我正在编写代码,它采用 .txt 文档并将该 .txt 文件每一行的每个单词存储在字符串列表中。但是我的代码出于某种随机原因决定要删除最后一个字符串的最后一个字母,谁能告诉我为什么?

我的代码:

import sys 
listofStr = [] 
print (" ")    
fname = input("Please enter file name: ") 
print (" ") 
 
try : 
    f = open(fname) 
 
    myLine = f.readline() 
    tuplist = [] 
    while (len(myLine)>0) : 
         strings = myLine[:-1] 
 
 
        listofStr.append(strings) 
        myLine = f.readline() 
 
 
 
    f.close() 
 
except IOError as e : 
     print("Problem opening file (Remember the file extension '.txt')") 
     sys.exit() 
 
print(listofStr)  

什么时候跑:

Please enter file name: test.txt 
 
['TEST', 'WAS', 'VERY', 'SUCCESSFU'] 

预期结果:

['TEST','WAS','VERY','SUCCESSFUL'] 

请您参考如下方法:

你正在分割没有换行符的最后一行:

strings = myLine[:-1] 

要解决此问题,您只需手动转到您的文件并附加一行。或者将上述行更改为 strings = myLine.strip()。无需手动对字符串进行切片,因为 strip 将处理空格和换行符。