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

2024-04-19 17:33:12 发布

您现在位置: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.close()

到目前为止,代码只是将以下内容输出到文本文件中:

Name Age BirthYear
name / 16 / 1999

页眉不是永久位于页面顶部。每个报头的对应信息应与报头对齐; 我希望它看起来像下面这样:

Name    Age  BirthYear  
Sam     22   1993
Bob     21   1992

必须在文本文件中。


Tags: 代码name信息inputageopenyearfile
3条回答

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

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

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

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

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

其中^8表示我希望字符串在8个字符之间居中。显然,您必须选择(或派生)适合您的数据的值。

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

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

相关问题 更多 >