我正在编写一个脚本,从用户那里获取输入并将其存储到文本文件中。它工作正常,但每次运行脚本时,我的文本文件都会被覆盖。 有没有办法永久保存数据,它不会被覆盖。
class reports:
def __init__(self):
self.BrandDetails= "Give details for Brands"
self.UserDetails = "Give details for Users"
def brands(self,bname,bid):
name=bname
id=bid
print("\t")
print "Brand name is ", name
print "Brand Id is", id
## return name, id
fp = open("test.txt","w")
fp.seek(6,2)
fp.write('\t')
fp.write('bname: %s, id: %s' % (bname or '', bid or ''))
fp.close()
print "\nFile data is: \t \n"
f=open('test.txt',"r+")
print f.read()
brand= reports()
print brand.BrandDetails
brand.brands(raw_input("Enter Brand name:"),
input("Enter Brand Id: "))
class users(reports):
def userdetails(self,uname,uid):
name=uname
id=uid
print("\t")
print "User name is ", name
print "User Id is", id
fp = open("test.txt","r+")
fp.seek(6,2)
fp.write('')
fp.write('uname: %s, uid: %s' % (uname or '', uid or ''))
fp.close()
print "\nFile data is: \t \n"
f=open('test.txt',"r+")
print f.read()
u=users()
print "\n\n"
print u.UserDetails
u.userdetails(raw_input("Enter User name:"),
input("Enter User Id: "))
我是python的新手。所以,我问这样的问题
答案 0 :(得分:0)
试试这个
#File : /tmp/test.py
class reports:
def __init__(self):
self.BrandDetails= "Give details for Brands"
self.UserDetails = "Give details for Users"
def brands(self, bname, bid):
name=bname
id=bid
fp = open('/tmp/test.txt', 'w')
fp.write('\t')
fp.write('bname: %s, id: %s' % (bname or '', bid or ''))
fp.close()
if __name__ == '__main__':
brand= reports()
print brand.BrandDetails
brand.brands(raw_input("Enter Brand name:"),
input("Enter Brand Id: "))
输出
python /tmp/test.py
Give details for Brands
Enter Brand name:Nile
Enter Brand Id: 123
[~]$ cat /tmp/test.txt
bname: Nile, id: 123