如何在python中的打开的txt文件中添加新行?

时间:2016-06-06 04:26:02

标签: python python-3.x

我试图通过更改打开的文件来编写程序,我需要在打印中添加一个新行。

在打开的txt.file中,它显示如下(我使用" _"替换空白):

名称_____高度(m)_____重量(kg)

比尔________ 1.58 __________ 58

玛丽_____ 1.65 __________ 43

...

现在我想添加一个像这样的新行: 姓名_____身高(m)_____体重(kg)_____年龄(年)< ---新的垂直线

比尔________ 1.58 __________ 58 _____________ 15

玛丽_____ 1.65 __________ 43 _____________ 17

我的代码是:

data_file = open("file.txt", "r")

print(data_file.read())

data_file.close()

那么,如何在打开的文件中添加另一条垂直线?此外,如果我想添加更多行,我该怎么做?

还有一件事,我使用的是python 3.5

2 个答案:

答案 0 :(得分:1)

我写了一个小班,去做你要求的所有事情。实施示例在底部完成。如果这对您有用,请告诉我。

class Feed(object):
    def __init__(self, file_name, sep, naming_convention=None):
        self.file_name = file_name
        self.feed_item_naming = naming_convention
        self.sep = sep
        self.feed = self.load_feed()

    def get_head(self, file=None):#lmao...
        '''
            Get the header
            '''

        if not file:
            head = open(self.file_name).readline().split(self.sep)
        else:
            head = file[0].split(self.sep)
        return head

    def __repr__(self):
        return repr(self.feed)

    def load_feed(self):
        '''
            load a feed object
            set the key of each item to the naming convention
            if we have multiple item names we increment the name bill becomes bill_2 and then bill_3 etc...
            '''

        #first we open the file and grab the headers
        file = [x.rstrip() for x in open(self.file_name).readlines()]
        self.header = self.get_head(file)
        if not self.feed_item_naming and self.feed_item_naming not in self.header:
            self.feed_item_naming = self.header[0]
        data = {}
        for line in file[1:]:
            if line != '':
                line = line.split(self.sep)
                pos = line[self.header.index(self.feed_item_naming)]
                while pos in data:
                    try:
                        ending = int(pos[-1])+1
                        pos.replace(pos[-1], ending)
                    except:
                        pos = pos+'_2'
                data[pos] = {}
                for item in self.header:
                    data[pos][item] = line[self.header.index(item)]
        return data

    def unload_feed(self, file_name=None, sep=None):
        '''
            write the modified feed back out to a data file
            '''

        if not file_name:
            file_name = self.file_name
        if not sep:
            sep = self.sep

        with open(file_name, 'wb') as file:
            for i in self.header:
                if i != self.header[-1]:
                    file.write(i+sep)
                else:
                    file.write(i)
            file.write('\n')
            for i in self.feed:
                for x in self.header:
                    if x != self.header[-1]:
                        file.write(str(self.feed[i][x])+sep)
                    else:
                        file.write(str(self.feed[i][x]))
                file.write('\n')


    def add_key(self, key, default_value=None):
        '''
            Add a key to each of the items
            '''
        if key not in self.header:
            for i in self.feed:
                self.feed[i][key]=default_value
            self.header.append(key)

    def get_key_value(self, item, key):
        '''
            get the value for the items key
            '''

        return self.feed[item][key]

    def get_item(self, item):
        '''
            get an individual item
            '''

        return self.feed[item]

    def set_key_value(self, item, key, value):
        '''
            set the value of each items key
            {item:{key:value, key:value}, item...etc}
            '''

        self.feed[item][key] = value

    def set_key_values(self, item, key_value_dict):
        '''
            set multiple key values for an item
            '''

        for k,v in key_value_dict.iteritems():
            self.set_key_value(item, k, v)

    def add_item(self, item):
        '''
            Add a new item
            '''
        while item in self.feed:
            try:
                end = str(int(item[-1])+1)
                item = item.replace(item[-1], end)
            except:
                item = item+'_2'

        self.feed[item] = {}
        self.feed[item][self.feed_item_naming] = item
        for i in self.header:
            if i != self.feed_item_naming:
                self.feed[item][i] = None

f = Feed('file.txt', '_____', 'Name') #initialize a new feed object, make sure that all seperators are the same for each item in your file
f.add_item('Angela') #add a new item
f.set_key_values('Angela', {'Height(m)':5, 'Weight(kg)':123}) #set the new items height and weight
f.add_key('Position')#create a new key for each item
f.unload_feed() #write the feed back to the file
print(f)

答案 1 :(得分:0)

如果通过"添加一条新的垂直线"你的意思是"添加一个新的"在您的文件中,您可以在csv模块的帮助下完成此操作。

以下代码的工作原理是将文件内容作为列表读取,进行更改,然后将更新后的列表写回文件。您也可以通过这种方式向文件中添加行。

import csv

with open('file.txt', 'r') as f:
    reader = list(csv.reader(f, delimiter=' ')) # if your file is delimited by spaces, tabs, etc. 
                                                # include that value here.  It appears that 
                                                # your file is space-delimited, but that's 
                                                # just a guess based on the info in your question.
    for i,row in enumerate(reader):
        if i == 0:
            row.append('Age(year)')
        if i == 1:
            row.append('15')
        if i == 2:
            row.append('17')

with open('file.txt','w') as f:
    wr = csv.writer(f, delimiter=' ')
    for row in reader:
        wr.writerow(row)

# file.txt output:
# Name Height(m) Weight(kg) Age(year)
# Bill 1.58 58 15
# Mary 1.6 43 17

在处理文件时,此代码也使用with语句。在处理文件时,使用withclose()(就像您提供的问题一样)是正确的做法。 with语句易于使用,因为它会自动关闭文件。