如何在Python中的.txt文件中添加头

如何在Python中的.txt文件中添加头,python,Python,我正在尝试为文本文件添加一个永久标题,标题中应包含相应的信息,即: 我的代码片段: name = input ("Name: ") age = input("Age: ") BirthYear = input("Birth Year: ") file = open ("info.txt", "a") file.write ("Name Age Grade\n") file.write ("{} / {} / {}\n".format(name, age, birthYear)) file.cl

我正在尝试为文本文件添加一个永久标题,标题中应包含相应的信息,即:

我的代码片段:

name = input ("Name: ")
age = input("Age: ")
BirthYear = input("Birth Year: ")

file = open ("info.txt", "a")
file.write ("Name Age Grade\n")
file.write ("{} / {} / {}\n".format(name, age, birthYear))
file.close()
到目前为止,代码仅将以下内容输出到文本文件中:

Name Age BirthYear
name / 16 / 1999
页眉不会永久位于页面顶部。每个表头对应的信息应与表头对齐; 我希望它看起来像下面这样:

Name    Age  BirthYear  
Sam     22   1993
Bob     21   1992

它必须位于文本文件中。

文本文件没有标题。如果你想要一个真正的标题,你需要一个更复杂的格式。或者,如果您只需要一些类似于页眉的内容,那么您需要计算页面上垂直放置的字符数,并每隔N行打印一次页眉

对于水平对齐,请使用可与
format()
一起使用的额外标记。例如:

>>> print('{a:^8}{b:^8}{c:^8}'.format(a='this', b='that', c='other'))
  this    that   other 

其中,
^8
表示我希望字符串以8个字符为中心。显然,您必须选择(或派生)适用于数据的值。

检查标题行是否已存在,如果第一行中不存在,则将其写入文件

name = input ("Name: ")
age = input("Age: ")
BirthYear = input("Birth Year: ")
filename = "info.txt"
header = "Name Age Grade\n"

def WriteHeader(filename, header):
    """
    ;param filename: a file path
    ;param header: a string representing the file's "header" row

    This function will check if the header exists in the first line
    and inserts the header if it doesn't exist
    """
    file = open(filename, 'r')
    lines = [line for line in file]
    file.close()
    if lines and lines[0] == header:
        # There are some lines in the file, and first line is the header
        return True
    else:
        # The first line is NOT the header
        file = open(filename, w)
        # Rewrite the file: append header if needed, and all lines which previously were there
        # excluding any misplaced header lines which were not at row 1
        file.write(header + ''.join([line for line in lines if not line == header]))
        file.close()
        return True


if __name__ == '__main__':
    if WriteHeader(filename, header):
        file = open(filename, 'a')
        file.write("{} / {} / {}\n".format(name, age, BirthYear))
        file.close()
    else:
        print 'there was some problems...'
仔细想想,这更简单:

def WriteHeader2(filename, header):
    # Always writes the header.
    file = open(filename, 'r')
    # remove any matching 'header' from the file, in case ther are duplicate header rows in the wrong places
    lines = [line for line in file if not line == header]
    file.close()

    # rewrite the file, appending the header to row 1
    file = open(filename, w)
    file.write(''.join([line for line in lines].insert(0,header))    
    file.close()

打开文件并写入头文件,然后使用新的with块循环并写入各个记录,怎么样?我遇到了你的问题,因为我还需要将标题打印到我的csv文本文件中。最后,我做了以下工作(使用您的示例):


使用
csv
模块可以显示更多代码吗?这是循环发生的吗?或者,是否要附加到现有文件?更多的上下文会有帮助…我的解释正确吗?您需要文本文件中的数据在视觉上对齐?@saarrrr是的,它必须在文本文件中正确对齐。@DavidZemens这是一个一般的想法,只是想看看如何在文本文件中获得标题,并将信息存储到有序的列和行中。在运行代码后,代码会为您创建一个文本文件。我认为这接近于他所需要的,为了100%确保您对齐,您需要首先聚合数据,并在每列中找到最长的条目,以便计算剩余或所需的空间缓冲区。当然,这只是一个示例,但感谢您提醒我们,OP可能不一定理解其含义。我加了一句话,说这不是OPs算法的精确解。好的,太好了,这不是我所期望的。在使其完全对齐方面,我可以做到,但当我想查看标题时,只需在文本文件的顶部有标题标题,这就是我想要的。因此,基本上,当我想附加文件时,头仍然存在。@MisterBob我不确定我是否理解头的问题是什么。你能为你的问题补充更多细节吗?附加到文件不会删除以前存在的内容。如果文件为空,则写入标题。如果没有,就继续正常的追加。哦,我明白了,我会试试这个。如果行[0]==头:索引器:列表索引超出范围如果
是一个空列表,你就必须考虑到这一点。。。试试
如果行和行[0]==标题:
OMG,非常感谢David,这太棒了,你到底是怎么想到再次感谢的。真的,这是100%个欢呼——如果你的问题有帮助的话,请考虑把它标记为“接受”:这个解决方案是因为我对文件类对象的各种状态的体验而来的,而你最初在“追加”模式中打开它时,你不能从中读取它。因此,您必须首先以“读取”模式打开它,以便检查其内容,然后以“写入”或“附加”模式重新打开,以便根据标题行是否存在来相应地处理文件。
header = "Name, Age, BirthYear"

with open('results.txt', 'a') as f:
    f.write(header + "\n")
    f.close

with open('results.txt', 'a') as f:

    for x in rows_sub:
        f.write(str(x) + ", " + c + "\n") #the line I needed to have printed via a loop