0

I mistakenly, typed the following code:

f = open('\TestFiles\'sample.txt', 'w')
f.write('I just wrote this line')
f.close()

I ran this code and even though I have mistakenly typed the above code, it is however a valid code because the second backslash ignores the single-quote and what I should get, according to my knowledge is a .txt file named "\TestFiles'sample" in my project folder. However when I navigated to the project folder, I could not find a file there.

However, if I do the same thing with a different filename for example. Like,

f = open('sample1.txt', 'w')
f.write('test')
f.close()

I find the 'sample.txt' file created in my folder. Is there a reason for the file to not being created even though the first code was valid according to my knowledge?

Also is there a way to mention a file relative to my project folder rather than mentioning the absolute path to a file? (For example I want to create a file called 'sample.txt' in a folder called 'TestFiles' inside my project folder. So without mentioning the absolute path to TestFiles folder, is there a way to mention the path to TestFiles folder relative to the project folder in Python when opening files?)

I am a beginner in Python and I hope someone could help me.

Thank you.

RMPR
  • 3,368
  • 4
  • 19
  • 31

3 Answers3

2

What you're looking for are relative paths, long story short, if you want to create a file called 'sample.txt' in a folder 'TestFiles' inside your project folder, you can do:

import os

f = open(os.path.join('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()

Or using the more recent pathlib module:

from pathlib import Path

f = open(Path('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()

But you need to keep in mind that it depends on where you started your Python interpreter (which is probably why you're not able to find "\TestFiles'sample" in your project folder, it's created elsewhere), to make sure everything works fine, you can do something like this instead:

from pathlib import Path

sample_path = Path(Path(__file__).parent, 'TestFiles', 'sample1.txt')

with open(sample_path, "w") as f:
    f.write('test')

By using a [context manager]{https://book.pythontips.com/en/latest/context_managers.html} you can avoid using f.close()

RMPR
  • 3,368
  • 4
  • 19
  • 31
1

When you create a file you can specify either an absolute filename or a relative filename. If you start the file path with '\' (on Win) or '/' it will be an absolute path. So in your first case you specified an absolute path, which is in fact:

from pathlib import Path

Path('\Testfile\'sample.txt').absolute()

WindowsPath("C:/Testfile'sample.txt")

Whenever you run some code in python, the relative paths that will be generate will be composed by your current folder, which is the folder from which you started the python interpreter, which you can check with:

import os
os.getcwd()

and the relative path that you added afterwards, so if you specify:

Path('Testfiles\sample.txt').absolute()

WindowsPath('C:/Users/user/Testfiles/sample.txt')

In general I suggest you use pathlib to handle paths. That makes it safer and cross platform. For example let's say that your scrip is under:

project
  src
    script.py
  testfiles

and you want to store/read a file in project/testfiles. What you can do is get the path for script.py with __file__ and build the path to project/testfiles

from pathlib import Path
src_path = Path(__file__)
testfiles_path = src_path.parent / 'testfiles'
sample_fname = testfiles_path / 'sample.txt'
with sample_fname.open('w') as f:
    f.write('yo')
dzang
  • 2,160
  • 2
  • 12
  • 21
0

As I am running the first code example in vscode, I'm getting a warning Anomalous backslash in string: '\T'. String constant might be missing an r prefix. And when I am running the file, it is also creating a file with the name \TestFiles'sample.txt. And it is being created in the same directory where the .py file is.

now, if your working tree is like this:

project_folder
    -testfiles
        -sample.txt
    -something.py

then you can just say: open("testfiles//hello.txt")

I hope you find it helpful.

fayez
  • 370
  • 1
  • 5
  • `open("testfiles//hello.txt")` this can be problematic if the path separator of your platform is not `/` – RMPR Oct 07 '20 at 14:22