Python文本文件布局
问题描述:
我希望能够以良好的布局布局来读写文本文件。Python文本文件布局
这是我到目前为止对文件进行读写的内容。非常基本但完美的工作。
写入文件:
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和TEAMNAME。 我需要它在这个布局或类似。
这种布局在文本文件名为database.txt
TEAMNAME: MISFITS, ID: 250
TEAMNAME: BLUES, ID: 170
TEAMNAME: EAZY, ID: 154
TEAMNAME: SUPER, ID: 124
该程序必须能够在此布局编写和在此布局读取。
感谢您的帮助提前! :)
答
你想要的是一个简单的.ini文件或适当的数据库文件。
一个.ini文件可以是这样的:
>>> 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)
...
在这里阅读更多:https://docs.python.org/3/library/configparser.html
更多
[Team1]
name=x
foo=1
bar=2
[Team2]
...
.ini文件可以在Python与configparser模块用来读取关于数据库文件的信息以及如何在Python中使用它们:https://docs.python.org/3/library/sqlite3.html
答
要读取您发布的布局,可以逐行读取文件,然后用逗号分隔每行。这些信息可以存储在字典中。
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()
您可以添加新条目列表如下:
data = readfile() #get the data
data.append({'TEAMNAME': 'COOL', 'ID': '444'})
writefile(data) #update the file
+0
谢谢你!正是我需要的。 :) –
欢迎到Stackoverflow! [如何问](https://stackoverflow.com/help/mcve) – bhansa