2

So my prof. gave me this code as the solution of my homework but when I run it it gives me an error. Can you please help me out? I guess I didn't specify the location of the file but not sure if that's the case.The objective of this question is to generate and read files that contain a list of random numbers.

import random
import os
import time


def fillFile(fileSize, fileName):

    # Delete file if exists
    if os.path.exists(fileName):
        os.remove(fileName)
    # Open file
    FILE = open(fileName, "w")

    # Write to file
    for i in range(fileSize):
        r = random.randint(0,fileSize+1000)
        FILE.write(str(r) + "\n")
    FILE.close()


def readFile(fileName):
    # Open file
    if os.path.exists(fileName):
        FILE = open(fileName,"r")
    else:
        print(fileName + " does not exist!")
        exit()

    # Read File
    alist = []
    for line in FILE:
        alist.append(int(line))

    FILE.close()

    return alist


def mainForFiles():
    # Dosyaları oluştur
    fileSizes = [1000, 5000, 10000, 25000, 50000, 100000, 200000]
    dirName = ".\\filesForAssignment1\\"

    # Delete fileStats.txt file if exists
    statFileName = "fileStats.txt"
    if os.path.exists(statFileName):
        os.remove(statFileName)

    # open stat file
    statFile = open(statFileName, "w")
    statFile.write("fillFile")

    print("WRITING TO FILES")

    for i in fileSizes:
        start = time.time()
        fillFile(i, dirName+"file"+str(i))
        finish = time.time()

        statFile.write("  " + str(finish-start))
        print("File Size = " + str(i) + "   Write Time = " + str(finish-start))

    statFile.write("\n")

    print("READING FILES")
    statFile.write("readFile")

    for i in fileSizes:

        fileName = dirName+"file"+str(i)

        # Dosyayı oku
        finish = time.time()
        alist = readFile(fileName)
        start = time.time()

        statFile.write("  " + str(finish-start))
        print ("File Size = " + str(i)+ "   Dosya Okuma Zamanı = " + str(finish-start))

    statFile.write("\n")
    statFile.close()


mainForFiles()
  File "C:/Users/emrea/PycharmProjects/helloworld/hello2.py", line 84, in 
<module>
    mainForFiles()
  File "C:/Users/emrea/PycharmProjects/helloworld/hello2.py", line 57, in mainForFiles
    fillFile(i, dirName+"file"+str(i))
  File "C:/Users/emrea/PycharmProjects/helloworld/hello2.py", line 12, in fillFile
    FILE = open(fileName, "w")
FileNotFoundError: [Errno 2] No such file or directory: '.\\filesForAssignment1\\file1000'
Emre Alpogunc
  • 51
  • 1
  • 9
  • please give full traceback while specifying errors in code – Sanchit.Jain Mar 05 '20 at 13:09
  • 1
    Just a wild guess (hence a comment and not an answer): you are using an IDE and the actual working directory is not what you expect and the directory `".\\filesForAssignment1\\"` is not present there. – Serge Ballesta Mar 05 '20 at 13:19
  • @Sanchit.Jain I updated the question.^^ – Emre Alpogunc Mar 05 '20 at 13:22
  • 1
    I had this problem once and discovered that python uses the main file folder path as source. So, if your reader script is in the same folder as your file, your path-to-file must be the path from your python main script. Besides that, do not forget to include file extension. If your script is in the same folder as your file, remove this '\\filesForAssignment1\\' from path xD Take a look if it'll help you (: – Dautomne_ Mar 05 '20 at 13:23
  • @Dautomne_ Thank you so much! I am trying it right now^^ – Emre Alpogunc Mar 05 '20 at 13:27

2 Answers2

2
FileNotFoundError: [Errno 2] No such file or directory: '.\\filesForAssignment1\\file1000'

The w mode causes the file to be created if it doesn't exist (and truncated if it does so the os.remove is not actually useful there), however it does expect intermediate directories to exist.

This means you should ensure the path to the file ('.\\filesForAssignment1) does exist before trying to create the file.

os.makedirs(os.path.dirname(fileName), exists_ok=True)

should do the trick, or

pathlib.Path(fileName).parent.mkdir(parents=True, exists_ok=True)

for a somewhat more modern take on it.

There's a bunch of other minor issues in the script:

  • the main function should generally be "gated" so modules can be imported without running them
  • explicitly closing files has fallen out of favor as it's unreliable
  • when opening files in "text" mode (the default) you should always provide an encoding
  • pathlib is fun, also that way you should not have to deal with path separators and all that crap
  • unless it's required to handle that case, I'd just let open(fname, 'r') error out if the file doesn't exist

Here's a version I think should be slightly improved:

import pathlib
import random
import os
import time


def fillFile(fileSize, fileName):
    with fileName.open('w', encoding='utf-8') as f:
        for i in range(fileSize):
            r = random.randint(0,fileSize+1000)
            f.write(f"{r}\n")

def readFile(fileName):
    with fileName.open(encoding='utf-8') as f:
        return [int(line) for line in f]

OUT_DIR = pathlib.Path.cwd().joinpath("filesForAssignment1")
FILE_SIZES = [1000, 5000, 10000, 25000, 50000, 100000, 200000]
def mainForFiles():
    # Dosyaları oluştur
    OUT_DIR.mkdir(parents=True, exist_ok=True) # make sure the directory exists

    statFilePath = pathlib.Path("fileStats.txt")
    with statFilePath.open('w', encoding='utf-8') as statFile:
        statFile.write("fillFile")

        print("WRITING TO FILES")

        for i in FILE_SIZES:
            start = time.time()
            fillFile(i, OUT_DIR.joinpath(f'file{i}'))
            finish = time.time()

            statFile.write(f"  {finish-start}")
            print(f"File Size = {i}   Write Time = {finish-start})")

        statFile.write("\n")

        print("READING FILES")
        statFile.write("readFile")

        for i in FILE_SIZES:
            f = OUT_DIR.joinpath(f'file{i}')

            # Dosyayı oku
            start = time.time()
            alist = readFile(f)
            finish = time.time()

            statFile.write(f"  {finish-start}")
            print (f"File Size = {i}   Dosya Okuma Zamanı = {finish-start}")

        statFile.write("\n")

if __name__ == '__main__':
    mainForFiles()
Masklinn
  • 34,759
  • 3
  • 38
  • 57
0

exit() is not doing what you want, it continues with the code.


def readFile(fileName):
    # Open file
    if os.path.exists(fileName):
        FILE = open(fileName,"r")
    else:
        print(fileName + " does not exist!")

        return

    # Read File
    alist = []
    for line in FILE:
        alist.append(int(line))

    FILE.close()

    return alist

Simone
  • 813
  • 8
  • 21