Python “显示”;“字符串索引超出范围”;使用循环时

Python “显示”;“字符串索引超出范围”;使用循环时,python,Python,我正在尝试编写一个代码,使每行的第一个字母都是大写的,但如果l[0],则无法执行超过第6行的代码。。islower():。l[0]在循环之外时工作正常,但当我将其放回循环时,它总是说“字符串索引超出范围” m = open(r"C:\Users\■■■■■■\Desktop\■■■■\other.txt","r", encoding = "utf-8") #Just blocking the text out while True:

我正在尝试编写一个代码,使每行的第一个字母都是大写的,但如果l[0],则无法执行超过第6行的代码。
。islower():
l[0]
在循环之外时工作正常,但当我将其放回循环时,它总是说“字符串索引超出范围”

m = open(r"C:\Users\■■■■■■\Desktop\■■■■\other.txt","r", encoding = "utf-8") #Just blocking the text out

while True:
    l = m.readline()

    if l[0].islower():
        l.replace(l[0],l[0].upper())
        
    print(l)
    
    if not l:
        break
m.close()

将检查放在循环的开头而不是结尾,因为即使
l
None
,您仍可以继续访问
l[0]

为True时:
l=m.读线()
如果不是l:
打破
如果l[0]。islower():
l、 替换(l[0],l[0].upper())
印刷品(l)
m、 关闭()
看,这可能是你想要的

您还可以更轻松地逐行迭代文件

path = r"other.txt"
with open(path, 'r') as file:
    for line in file:
        print(line.capitalize())

您可以使用它。

请也共享输入文件的内容。为什么要这样循环?为什么不只为m中的行
?无论如何,您应该在阅读
l
之后立即放置
if not l
,而不是放在末尾。另外,执行
replace(l[0],…)
将替换该字母的所有匹配项,而不仅仅是第一个
with open("content.txt", 'r') as file:

    while 1:
        content = file.readline()
        if not content:
            break

        print(content.capitalize())

print("Done !")