0

I want to create a csv file and read from it using a random token as a filename, However, it returns an error by creating a file.

import secrets
import os
import pandas as pd


views_data_dir = 'views_data'

def rnd_token():
    return str(secrets.token_hex(nbytes=128))


def convert_csv(csv):
    rnd_token = rnd_token()
    name = f'./{views_data_dir}/{rnd_token}.csv'
    print(name)
    if not os.path.exists(name):
        # error happens here
        with open(name, 'wb') as f:
            # Perform byte join on the CSV data
            f.write(b''.join(csv))
    return get_df(rnd_token)


def get_df(rnd_token):
    print(rnd_token)
    df = pd.read_csv(f'./{views_data_dir}/{rnd_token}.csv', header=0)
    return df


FileNotFoundError: [Errno 2] No such file or directory: './views_data/c7f7b45b8fb8261fb021ada872a3885055bfce7b61533dfb53241bd6958f396c6496e8577477e3e5c49dd2adf1f73b1a6f931cca84ad084729f4933c0e97b79a5ac1d1dea29378903d1c85863bb9910d429c4389f5bfbc6df464648c9cb0e74ee0365b
46464275ec07118621aa4e7bf7dd1c821b562ef50d38dac17055e52241.csv'

But when I pass some filename such as "test" or so on it creates the file without errors. I have tried "wb+" mode but it did not help. The function creates a file without name ".csv".

Anna
  • 914
  • 9
  • 25
  • Note that the error says "No such file **or directory**". Does `./views_data ` exist? – MisterMiyagi Dec 20 '21 at 08:44
  • @MisterMiyagi yeah I have created it before and the path is ok – Anna Dec 20 '21 at 08:45
  • Please confirm the path. `print(f'{os.getcwd()}/{views_data_dir}')` – dudulu Dec 20 '21 at 08:48
  • I think that your filename is too long (256 characters). Maybe try it with another smaller name just to test if there is an error in your code or that the large filename gives you problems. – 3dSpatialUser Dec 20 '21 at 08:49
  • @3DspatialUser it is exactly 256 characters, I have tried to remove the last 2 chars from the token ([:-2]) it still generates the error. However when I try with the filename like "test" or "file" it actually creates the file with no errors. – Anna Dec 20 '21 at 08:56
  • Maybe this question/answer can help you. I think that your path is still too long, even if you shorten the filename only with 2 characters. https://stackoverflow.com/questions/3555527/python-win32-filename-length-workaround/3557977. – 3dSpatialUser Dec 20 '21 at 08:58

0 Answers0