我在文件夹中有几个文本文件,其中包含名称和形容词列表。我设法创建了一个脚本,它采用随机名称,秒名等,并从该数据创建一个字符。
我正在使用的是以下代码,它从文本文件中获取所有行并将它们放在一个数组中(此方法到目前为止一直运行良好):
file=open("file_name","r")
array_name = []
for line in file:
array_name.append( line.rstrip('\n') )
(Repeat this for every text file)
我从中获取数据的来源通常格式不正确(一切都在大写,没有大写等等),所以我试图创建另一段代码来大写所有这些文本文件中的每个单词。经过广泛搜索后,我发现title()完全符合我的要求,而我正在尝试使用前面代码的一部分来实现该方法。
我遇到了一些麻烦,特别是因为显然我创建了一段代码来完成我想要的但实际上并没有将更改写入文件。这就是我所做的:
file=open("file_name","r+")
for line in file:
line=line.title()
file.close
想法是以读写模式打开文件,读取一行,将该行更改为应用了title()的同一行并重复直到文件末尾。
我忘了添加一些东西吗?我一直在尝试和思考它已经有一段时间了,我无法做到这一点。我假设问题出在line = line.title()行中,但我的所有尝试都以文本文件为空或以其他方式搞砸而结束。
答案 0 :(得分:1)
首先,使用上下文管理器with
语句:
with open('file_name', 'r+') as my_file: # this automatically closes it
lines = my_file.readlines()
# now, rewrite the data
for line in lines:
my_file.write(line.title())
编辑:要完全重写数据,你必须使用'w+'
缓冲模式(所以首先你可以读取它,而不是写原始数据),并将文件指针设置回到开头的文件:
with open('file_name', 'w+') as my_file:
lines = my_file.readlines()
# set the file pointer at the beginning of the file
my_file.seek(0, 0)
# now, rewrite the data
for line in lines:
my_file.write(line.title())
上一个问题(我的第一个例子)是,一旦你完全读完文件,文件指针就在文件的末尾。因此,你必须将它设置回文件的末尾。开始使用file.seek
方法。
答案 1 :(得分:0)
def main():
words = {}
for whichfile in ['firstname', 'lastname', 'noun', 'adjective']:
# read all words from file
with open(whichfile + '.txt') as inf:
words[whichfile] = [line.strip().title() for line in inf]
# write capitalized words back to file
with open(whichfile + '.txt', 'w') as outf:
outf.write('\n'.join(words[whichfile]))
if __name__=="__main__":
main()