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

2024-09-19 23:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

公开的txt文件,如下所示(我使用“”替换空白):

姓名身高(m)体重(kg)

1.58比尔

Mary_优逯uu轱u1.65轱uuuuu43

。。。在

现在我想添加一个新的行,如下所示: 名称-高度(m)、重量(kg)、年龄(年)<;——新的垂直线

清单15

玛莉廑

我的代码是:


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

print(data_file.read())

data_file.close()

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


还有一件事,我使用python3.5


Tags: 文件程序txt名称data高度空白file
2条回答

如果“addanewverticalline”的意思是“addanewolumn”,那么可以借助^{}模块来实现这一点。在

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

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语句。在处理文件时,使用^{}^{}(就像你在问题中提到的那样)是正确的做法。with语句很容易使用,因为它会自动关闭文件。在

我写了一个小类来完成你要求的一切。实现示例在底部完成。告诉我这对你有用吗。在

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)

相关问题 更多 >