简体   繁体   English

Python代码未写入文件

[英]Python code not writing into file

I have several text files in a folder, containing a list of names and adjectives. 我在一个文件夹中有几个文本文件,其中包含名称和形容词的列表。 I have managed to create a script that takes random names, second names and such and creates a character from that data. 我设法创建了一个脚本,该脚本采用随机名称,第二个名称等,并根据该数据创建一个字符。

What I am using for that is the following code, which takes all the lines from the text file and places them in an array (This approach has worked well so far): 我为此使用的是以下代码,该代码从文本文件中提取所有行并将它们放置在数组中(到目前为止,此方法效果很好):

file=open("file_name","r")
array_name = []
for line in file:
    array_name.append( line.rstrip('\n') )

(Repeat this for every text file)

The sources I take that data from are often badly formatted (Everything in caps, nothing capitalised, etc), so I am trying to create another piece of code that capitalises every single word in all those text files. 我从中获取数据的来源通常格式不正确(大写形式,大写形式,等等),因此我试图创建另一段代码,将所有这些文本文件中的每个单词都大写。 After extensive searching I've found that title() does exactly what I want to do, and I am trying to implement that approach using part of the previous code. 经过广泛的搜索,我发现title()确实可以完成我想做的事情,并且我试图使用前面的代码的一部分来实现该方法。

I am running into some trouble, especially because apparently I have created a piece of code that does what I want but does not actually write the changes to the file. 我遇到了一些麻烦,特别是因为显然我创建了一段代码,该代码可以执行我想要的操作,但实际上并未将更改写入文件中。 Here is what I have done: 这是我所做的:

file=open("file_name","r+")
for line in file:
    line=line.title()
file.close

The idea is to open the file in read and write mode, read a line, change that line to the same line with title() applied and repeat until the end of the file. 这个想法是在读取和写入模式下打开文件,读取一行,将该行更改为应用了title()的同一行,然后重复执行直到文件结束。

Am I forgetting to add something? 我是否忘记添加某些内容? I have been trying things and thinking about it for some time now and I am not able to make this work. 我已经尝试了一段时间并考虑了一段时间,但我无法完成这项工作。 I am assuming the problem is in the line=line.title() line, but all my attempts have ended with the text files being empty or screwed up in some other way. 我假设问题出在line = line.title()行中,但是我的所有尝试都以文本文件为空或以其他某种方式破坏而结束。

First, use a context manager, the with statement: 首先,使用上下文管理器, 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())

Edit: to completely rewrite the data, you have to use a 'w+' buffer mode (so first you can read it, than write over the original data) and also set the file pointer back to the beginning of the file: 编辑:要完全重写数据,您必须使用'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())

The previous issue (with my first example) is that once you have fully read the file, the file pointer is at the end of the file. 上一个问题(在我的第一个示例中)是,一旦您完全读取了文件, 文件指针就位于文件的末尾。 Thus, you have to set it back to the beginning using the file.seek method. 因此,您必须使用file.seek方法将其重新设置为开始。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM