-2

In the past week, I spent my time trying to solve a big problem when compiling my program.py. My program script is:

import numpy
import matplotlib
import matplotlib.pyplot as plt
import scipy.interpolate
from matplotlib.font_manager import FontProperties
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
import os
#import pathlib
#from pathlib import Path


font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')
marker_size = .5
font_size = 20.

font_size_labels = 50
font_weight = 'bold'

# Generate data:
file_path = r'C:\Users\annyc\Desktop\gap.txt' #the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing.
#file_name = os.path.basename(file_path)
x, y, z, center = numpy.loadtxt(file_path, dtype='float64', delimiter='\t', unpack=True)

# Set up a regular grid of interpolation points
xi, yi = numpy.linspace(x.min(), x.max(), 500), numpy.linspace(y.min(), y.max(), 500)
xi, yi = numpy.meshgrid(xi, yi)

fig = plt.figure(figsize=(10,15))
ax1 = fig.add_subplot()

for axis in ['top','bottom','left','right']:
    ax1.spines[axis].set_linewidth(3)

# Interpolate
zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='linear')

ax2 = fig.add_subplot()

im = plt.imshow(zi, vmin=0., vmax=1, origin='lower', aspect = "auto", cmap='hot',
           extent=[x.min(), x.max(), y.min(), y.max()])
ax2_divider = make_axes_locatable(ax2)

plt.xlabel('R', fontproperties=font, fontsize=font_size)
plt.xticks(size=15)
plt.tick_params(width=3, length=10)
plt.ylabel(r'$\delta$', fontproperties=font, fontsize=font_size)
plt.yticks(size=15)
#plt.title('(a)', fontproperties=font, fontsize=font_size, pad=0.5)

#plt.scatter(x, y, c=z)

levels = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
manual_locations = [(2.5, 10), (1, 10), (2, 60), (1.5, 70), (1, 70), (0.75, 80), (2.5, 40), (2, 60)]



contour = plt.contour(xi, yi, zi, colors='green', linestyles='dashdot', linewidths = 2)
plt.clabel(contour, colors = 'green', fmt = '%2.1f', fontsize=15, manual=manual_locations)

#cbar = plt.colorbar(im, ticks=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], shrink=1., aspect=20.,
#                    orientation='horizontal', pad = 0.25)

cax2 = ax2_divider.append_axes("top", size=.3, pad=0.75)
cbar2 = fig.colorbar(im, cax=cax2, ticks=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
                    orientation='horizontal')
cbar2.set_label('Bandgap Width', fontproperties=font, fontsize=font_size)
cbar2.ax.tick_params(labelsize=17, width=3, direction='in', length=10)
cbar2.outline.set_edgecolor('black')
cbar2.outline.set_linewidth(3)

#plt.savefig('gap_r_delta.pdf')
plt.savefig('gap_r_delta.png', dpi=600)
plt.show()

and the error that insists on appearing when I compile this program is:

Traceback (most recent call last):
  File "C: \ Users \ annyc \ Desktop \ data \ 3d_contour.py", line 24, in <module>
    x, y, z, center = numpy.loadtxt (file_path, dtype = 'float64', delimiter = '\ t', unpack = True)
  File "C: \ Users \ annyc \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ numpy \ lib \ npyio.py", line 961, in loadtxt
    fh = np.lib._datasource.open (fname, 'rt', encoding = encoding)
  File "C: \ Users \ annyc \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ numpy \ lib \ _datasource.py", line 195, in open
    return ds.open (path, mode, encoding = encoding, newline = newline)
  File "C: \ Users \ annyc \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ numpy \ lib \ _datasource.py", line 535, in open
    raise IOError ("% s not found."% path)
OSError: C: \ Users \ annyc \ Desktop \ gap.txt not found.

I don't know how to solve this problem since the gap.txt file is in the same folder as the program.py.

Could someone tell me what I did wrong? Thanks!

G5W
  • 36,531
  • 10
  • 47
  • 80
  • Are you sure the file in the Desktop folder is named "gap.txt"? Are you showing or hiding file extensions in File Explorer? – Nayuki Aug 17 '20 at 13:50
  • From your traceback it doesnt look like they are in the same folder, try `Shift`+`Rightclick` on your gap.txt (in the win explorer) -> copy as path, then paste the path as `file_path`, and try again. – Josef Aug 17 '20 at 13:52
  • Try using filepath = os.path.abspath('.') + '/gap.txt' – Rahul Vishwakarma Aug 17 '20 at 13:59

1 Answers1

0

Python knows how to handle windows paths with unix-like path strings using forward slashes.

Change C:\Users\annyc\Desktop\gap.txt to C:/Users/annyc/Desktop/gap.txt

You can also check os.path.exists("C:/Users/annyc/Desktop/gap.txt") to make sure the file is actually where you say it is.

This answer has a lot of good info about paths

JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • I'm pretty sure pyhon can handle both cases. With `os.sep` you can actually see the default seperator for your os. – Josef Aug 17 '20 at 14:14