Python文本文件布局
我希望能够在一个良好的布局中读写文本文件 以下是我到目前为止在文件上读写的内容。非常基本,但工作做得很完美 写入文件:Python文本文件布局,python,python-3.x,text-files,Python,Python 3.x,Text Files,我希望能够在一个良好的布局中读写文本文件 以下是我到目前为止在文件上读写的内容。非常基本,但工作做得很完美 写入文件: def writefile(): file = open("database.txt","w") file.write("Testing.. Testing.. 123.") file.close() print("Written on file [database.txt] successful") def readfile():
def writefile():
file = open("database.txt","w")
file.write("Testing.. Testing.. 123.")
file.close()
print("Written on file [database.txt] successful")
def readfile():
file = open("database.txt","r")
print(file.read())
file.close()
正在读取文件:
def writefile():
file = open("database.txt","w")
file.write("Testing.. Testing.. 123.")
file.close()
print("Written on file [database.txt] successful")
def readfile():
file = open("database.txt","r")
print(file.read())
file.close()
但是,我需要它,以便我可以在一个文件中正确处理ID和团队名称。
我需要它在这个布局或类似的
此布局在名为database.txt的文本文件中
TEAMNAME: MISFITS, ID: 250
TEAMNAME: BLUES, ID: 170
TEAMNAME: EAZY, ID: 154
TEAMNAME: SUPER, ID: 124
程序必须能够在此布局中写入和读取
提前感谢您的帮助!:) 您需要的是一个简单的.ini文件或一个适当的数据库文件 .ini文件可以如下所示:
[Team1]
name=x
foo=1
bar=2
[Team2]
...
data = readfile() #get the data
data.append({'TEAMNAME': 'COOL', 'ID': '444'})
writefile(data) #update the file
.ini文件可以通过configparser模块在Python中读取:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
请在此处阅读更多信息:
有关数据库文件以及如何在Python中使用它们的详细信息:要在发布的布局中阅读,可以逐行阅读文件,然后在逗号处拆分每一行。然后可以将这些信息存储在词典中
def readfile():
datalist = [] #create a list to store the dictionaries in
file = open('database.txt', 'r')
lines = file.read().split('\n') #this creates a list containing each line
for entry in lines: #scan over all of the lines
parts = entry.split(',') #split it at the comma
dictionary = dict()
for part in parts:
dictionary[part.split(':')[0].strip()] = part.split(':')[1].strip()
datalist.append(dictionary)
file.close()
return datalist
datalist
是一个包含字典的列表,其中包含信息。它可以这样使用:
for item in datalist:
print('Team Name:', item['TEAMNAME'])
print('Id:', item['ID'])
要回写文件,可以使用以下方法:
def writefile(datalist):
file = open('database.txt', 'w')
for entry in datalist:
output = ''
for key in entry.keys():
output += key
output += ': '
output += entry[key]
output += ', '
file.write(output[:-2] + '\n') #get rid of the trailing comma
file.close()
您可以向列表中添加新条目,如下所示:
[Team1]
name=x
foo=1
bar=2
[Team2]
...
data = readfile() #get the data
data.append({'TEAMNAME': 'COOL', 'ID': '444'})
writefile(data) #update the file
欢迎来到Stackoverflow!