vscode作为编辑器运行python,但是运行时读取不了文件,debug时却没有问题

小白求问,今天装了vscode的最新版,然后按照网上教程装好了python的插件,然后运行python程序时出现了问题。代码如下:

import json
from collections import defaultdict
from collections import Counter

from pylab import *
import matplotlib.pyplot as plt
from pandas import DataFrame, Series
import pandas as pd;
import numpy as np

path = 'usagov_bitly_data2012-03-16-1331923249.txt'

records = [json.loads(line) for line in open(path)]

# for i in range(len(records)):
# for k, v in records[i].items():
# print(k, v)

print(len(records))
print(records[0]['tz'])

time_zones = [rec['tz'] for rec in records if 'tz' in rec]

print(time_zones[:10])


def get_counts(sequence):
    counts = defaultdict(int)
    for x in sequence:
        counts[x] += 1
    return counts


counts = get_counts(time_zones)

print(counts['America/New_York'])
print(len(time_zones))


def top_counts(count_dict, n=10):
    value_key_pairs = [(count, tz) for tz, count in count_dict.items()]
    value_key_pairs.sort()
    return value_key_pairs[-n:]


print(top_counts(counts))

print(Counter(time_zones).most_common(10))

frame = DataFrame(records)

print(type(frame))

print(frame['tz'][:10])

tz_counts = frame['tz'].value_counts()
print(tz_counts[:10])

clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unknown'
tz_counts = clean_tz.value_counts()
print(tz_counts[:10])

tz_counts[:10].plot(kind='barh', rot=0)
# plt.show()

print(frame['a'][1])
print(frame['a'][50])
print(frame['a'][51])

results = Series([x.split()[0] for x in frame.a.dropna()])
print(results[:5])
print(results.value_counts()[:8])

cframe = frame[frame.a.notnull()]
operating_systems = np.where(cframe['a'].str.contains('Windows'), 'Windows', 'Not Windows')
print(operating_systems[:5])

by_tz_os = cframe.groupby(['tz', operating_systems])
agg_counts = by_tz_os.size().unstack().fillna(0)

print(agg_counts[:10])

indexer = agg_counts.sum(1).argsort()
print(indexer[:10])

count_subset = agg_counts.take(indexer)[-10:]
print(count_subset)
count_subset.plot(kind='barh',stacked=True)

normed_subset = count_subset.div(count_subset.sum(1),axis=0)
normed_subset.plot(kind='barh',stacked=True)
plt.show()

运行时,报错显示

[Errno 2] No such file or directory: 'usagov_bitly_data2012-03-16-1331923249.txt'

然后进行debug,用integrated Terminal/Console进行调试没有问题,可以得到结果。然后重新去运行这个程序的时候,发现还是同样的报错。
求温大神这是为什么?该怎样解决?万分感谢。
图片描述
图片描述

阅读 7.1k
1 个回答

估计是 vscode 执行时 current dir 和 py 文件不在同一个目录中,这点可以通过 import os; print(os.getcwd()) 验证一下。

建议这样修改:

import os.path as p
path = p.join(p.dirname(__file__), 'usagov_bitly_data2012-03-16-1331923249.txt')

records = [json.loads(line) for line in open(path)]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏