我正在尝试为文本文件添加永久标头,并且标题应该有相应的信息,即:
我的代码段:
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
它必须位于文本文件中。
答案 0 :(得分:3)
文本文件没有标题。如果你想要一个真正的标题,你需要一个更复杂的格式。或者,如果你只是需要一些像标题一样的东西,那么你需要弄清楚你的页面上垂直有多少个字符,并且每N行打印一个标题。
对于水平对齐,请使用可与format()
一起使用的额外令牌。举个例子:
>>> print('{a:^8}{b:^8}{c:^8}'.format(a='this', b='that', c='other'))
this that other
其中^8
表示我希望字符串以8个字符为中心。显然,您必须选择(或派生)适用于您的数据的值。
答案 1 :(得分:1)
如何打开文件并在标题中写入,然后使用新的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
答案 2 :(得分:0)
检查标题行是否已存在,如果第一行中不存在,则将其写入文件。
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()