简体   繁体   中英

Why can't I import a file.dat using a program in python (I manage to do it only from the console)?

I have a file data1.dat in the same folder as my code.py . This is what I write to import from the data1.dat

import pandas as pd

#read data as csv to a dataframe
x = pd.read_csv('data1.dat', sep=",", header=None)
print (x)

Then i try to convert it to an array using x.to_numpy but my pandas version is too old. Trying to update it writing: conda install -c anaconda pandas inside anaconda prompt resolves in this issue: ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'anaconda::tqdm-4.50.2-py_0'. CondaError: Cannot link a source that does not exist. C:\Users\domyb\Anaconda3\Scripts\conda.exe Running conda clean --packages may resolve your problem. Attempting to roll back.

CondaError: Cannot link a source that does not exist. C:\Users\domyb\Anaconda3\Scripts\conda.exe Running conda clean --packages may resolve your problem. Any idea?

By default, the path is relative to the current working directory, which can change, depending where/how you execute your script.

If the .dat file will always be present in the same directory as the Python file, make the file path relative to the current file.

import pathlib
import pandas as pd

this_directory = pathlib.Path(__file__).parent
dat_file = this_directory / 'data1.dat'

pd.read_csv(dat_file, sep=',', header=None)

If you're using a version of Python that does not have pathlib , you can do this:

import os

this_directory = os.path.abspath(os.path.dirname(__file__))
dat_file = os.path.join(this_directory, 'data1.dat')
# ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM