2014-01-25 28 views
0

我想在Python中的文件中写一个输出结果,但它不工作既没有显示任何错误。写输出到文件不工作:没有发现错误

以下是我的代码:

from collections import namedtuple 
from pprint import pprint as pp 

final_data = [] 
inf = float('inf') 
Edge = namedtuple('Edge', 'start, end, cost') 
class Graph(): 
def __init__(self, edges): 
    self.edges = edges2 = [Edge(*edge) for edge in edges] 
    self.vertices = set(sum(([e.start, e.end] for e in edges2), [])) 

def dijkstra(self, source, dest): 
    assert source in self.vertices 
    dist = {vertex: inf for vertex in self.vertices} 
    previous = {vertex: None for vertex in self.vertices} 
    dist[source] = 0 
    q = self.vertices.copy() 
    neighbours = {vertex: set() for vertex in self.vertices} 
    for start, end, cost in self.edges: 
     neighbours[start].add((end, cost)) 
    #pp(neighbours) 

    while q: 
     u = min(q, key=lambda vertex: dist[vertex]) 
     q.remove(u) 
     if dist[u] == inf or u == dest: 
      break 
     for v, cost in neighbours[u]: 
      alt = dist[u] + cost 
      if alt < dist[v]:         
       dist[v] = alt 
       previous[v] = u 
    #pp(previous) 
    s, u = [], dest 
    while previous[u]: 
     s.insert(0, u) 
     u = previous[u] 
    s.insert(0, u) 
    return s 

start_point = input('Enter the starting point: ') 
end_point = input('Enter the ending point: ') 
file_name = input('Enter the input file name: ') 
output_file = input('Enter the output file name: ') 
f = open(file_name, 'r') 

data = f.readlines() 

for line in data: 
    f_line = line 
    values = f_line.split() 
    values[2] = int(values[2]) 
    final_data.append(values) 

graph = Graph(final_data) 




f = open(output_file, 'a') 

result = str(pp(graph.dijkstra(start_point, end_point))) 
f.write(result) 

注:忽略缺口

我不知道究竟我在哪里做的错误。我尝试使用append(a)和write(w)写入文件,但两者都不起作用。文件的所有路径都是正确的,并且输入文件正在完美读取,并且输出文件也位于同一文件夹中。

+1

你忘了'f.close()'结尾。 –

+0

感谢您的帮助,但现在它的文字没有确切的答案 –

+1

这是因为'pprint.pprint'返回'None'。 –

回答

1
f = open(output_file, 'a') 
result = str(pp(graph.dijkstra(start_point, end_point))) 
f.write(result) 

你想代替:

with open(output_file, 'a') as f: 
    result = pprint.pformat(graph.dijkstra(start_point, end_point)) 
    f.write(result) 

因为pprint.pprint()是更换print,因而具有相同的 “原型”,它没有返回值。 pprint.pformat已被创建,因此您可以“打印”为字符串。虽然,你可能想要做

with open(output_file, 'a') as f: 
    pp(graph.dijkstra(start_point, end_point), stream=f) 

为pprint国家的帮助:

Help on function pprint in module pprint: 

pprint(object, stream=None, indent=1, width=80, depth=None) 
    Pretty-print a Python object to a stream [default is sys.stdout].