我是编码和学习python的新手。我一直在尝试创建一个程序,询问有关零件的用户信息,然后将其附加到文件中。一旦它附加文件,我应该能够看到文件中的信息,如果我打开它。但是,程序不会将信息保存在文件中。我可能会犯一个愚蠢的错误,但我无法弄明白,因为我对编码完全不熟悉。
import sys
import pandas as pd
colnames = ['name', 'numid', 'length', 'height']
parts_info = pd.read_csv('part.info', sep ='\t', header = None, names = colnames, index_col = 'name')
New_parts = {}
class Part:
name = ""
numid = 0
height = 0
length = 0
def display(self):
print ''
print 'Part Information:'
print parts_info
def get(self):
self.name = raw_input('Enter Part Name: ')
self.numid = int(raw_input('Enter NumId: '))
self.height = float(raw_input('Enter Height (in feet): '))
self.length = int(raw_input('Enter Length: '))
def new_part(self):
New_parts[self.name] = {'numid':self.numid, 'height':self.height, 'length':self.length}
def save(self):
with open('part.info','a') as f:
parts_info.to_csv(f, header = False)
f.close()
onePart = None
if len(sys.argv) > 1 and sys.argv[1] == 'READ':
onePart = Part()
else:
onePart = Part()
onePart.get()
onePart.new_part()
onePart.save()
New_df = pd.DataFrame.from_dict(New_parts,orient='index')
New_df.index.name = 'name'
parts_info = parts_info.append(New_df)
onePart.display()
答案 0 :(得分:0)
有几件事:
使用pd.read_csv
时,无需定义列名称,将根据default header=
argument从csv
推断出列名称。 index_col=
也应该是int
。您可以阅读
parts_info = pd.read_csv('part.info', sep ='\t', index_col=0)
调用.save()
时,尚未将任何数据附加到DataFrame。放入一些print
语句,以便您可以看到流程,例如
def save(self):
print 'saving', parts_info
with open('part.info','a') as f:
parts_info.to_csv(f, header = False)
或
print 'make new part'
onePart = Part()
print 'get new part info'
onePart.get()
print 'add to log'
onePart.new_part()
print 'save it to csv'
onePart.save()
您需要重新构建代码,以便按照您希望的顺序进行操作。
使用时
with open('/path/to/file', 'a') as f:
你不需要
f.close()
请参阅with
声明背后的best practice。