Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

Python 打开一个文本文件,转换为第一个字母为大写,其余字母为小写

Python 打开一个文本文件,转换为第一个字母为大写,其余字母为小写,python,python-3.x,Python,Python 3.x,我有一个文本文件 I BLESS THE RAINS DOWN IN AFRICA 我需要对它进行转换,所有的第一个字母都是大写的,其余的都是小写的。第二部分是我需要将转换后的文本写入一个新的文本文档 text_file = open('lyrics.txt','r') 这就是你想要的吗 with open('file.txt','r') as f: newl = [] l = f.readlines() for i in l: newl.append(s

我有一个文本文件

I
BLESS 
THE 
RAINS
DOWN
IN 
AFRICA
我需要对它进行转换,所有的第一个字母都是大写的,其余的都是小写的。第二部分是我需要将转换后的文本写入一个新的文本文档

text_file = open('lyrics.txt','r')

这就是你想要的吗

with open('file.txt','r') as f:
   newl = []
   l = f.readlines()
   for i in l:
      newl.append(str(i[0]+i[1:].lower()).strip())
with open('new.txt','w') as f2:
   for i in newl:
      f2.write(i+'\n')
您可以对文件的内容使用该方法

with open("lyrics.txt") as f:
    s = f.read().title()

with open("lyrics.txt", "w") as f:
    f.write(s)
您可以将所有这些内容放在一个上下文管理器中,但我发现上面的内容比

with open("lyrics.txt", "r+") as f:
    s = f.read().title()
    f.seek(0)
    f.write(s)

每行只有一个单词吗?如果每行有多个单词,它们的所有首字母都应该大写,还是只打印该行的第一个字母?每行一个单词如何将其插入到新创建的文本文件中?是否有方法使输出打印在不同的行上,如原始行,而不是一行?