No such file or directory: 'train_art_path' - python-3.x

I am trying to read documents from a file path using a Jupyter Notebook as follows.
train_art_path = "/work/TEXT_SUMMARIZATION/train_dialogue.txt"
with open(train_art_path, 'r') as file:
a=file.readlines()
print(a)
print('\n')
I get the following issue:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
/tmp/ipykernel_79659/545421924.py in <module>
----> 1 with open(train_art_path, 'r') as file:
2 a=file.readlines()
3 print(a)
4 print('\n')
FileNotFoundError: [Errno 2] No such file or directory: 'train_art_path'
Alternatively, I tried to read documents as follows. It works perfectly.
with open('train_dialogue.txt', 'r') as file:
a=file.readlines()
print(a)
print('\n')
Can you please help me to solve the first one? Thanks in Advance.

You are using train_art_path as a variable, so should not have quotes ' after assignment. Change...
with open('train_art_path', 'r') as file:
to
with open(train_art_path, 'r') as file:

Related

AttributeError: 'str' object has no attribute 'write' when adding a string to a txt.file

I am trying to learn how to open txt.files on Python 3.7.
I have a file (Days.txt) with the following content:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
On Jupyter, I used the following code:
f = open('Days.txt','r').read()
f
which gave me the following result:
'Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday'
so far, so good.
Then, I tried to add a sentence to the Days.txt file by:
f.write('this is a test\n')
and that's where I get the below error message:
AttributeError Traceback (most recent call last)
in
----> 1 f.write('this is a test\n')
AttributeError: 'str' object has no attribute 'write'
Why isn't it working?
The code below results in another error message:
file = open('Days.txt','r')
s = file.read()
file.write('this is a test\n')
file.close()
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-138-0cc4cd12a8b3> in <module>
1 file = open('Days.txt','r')
2 s = file.read()
----> 3 file.write('this is a test\n')
4 file.close()
UnsupportedOperation: not writable
Because f is a string, not the file pointer, it's better to keep the file pointer in its own variable:
f = open('Days.txt', 'r')
s = f.read() # <-- check the content if you need it
print(s)
f.write('this is a test\n')
f.close() # <-- remember to close the file
Better yet to automatically close the file:
with open('Days.txt', 'r') as f:
s = f.read()
print(s)
f.write('this is a test\n')
Open the file in write mode to allow adding new contents to it.
To do so, just
f = open("Days.txt", "a")
f.write("This is a text\n")
f.close()
Remember to close the file handler after opening it.
I however suggest you to use the "with" construct, that automatically closes the file handler after the read/write operation
with open("Days.txt", "a") as f:
f.write("This is a text\n")

Having problems with python putting 2 backslashes in path

I have this problem that python puts 2 backlashes in an path and I don't understand why.
Here is the code:
with open(os.path.join("Users", "Kasutaja", "AppData", "Local", "Growtopia", "save.dat"), 'r+') as f:
file_data = f.read()
It gives me this=
C:\Users\Kasutaja\AppData\Local\Programs\Python\Python39\python.exe "C:/Users/Kasutaja/Desktop/Growtopia Hack.py"
Game not found! Make sure to open this before Growtopia
Traceback (most recent call last):
File "C:\Users\Kasutaja\Desktop\Growtopia Hack.py", line 61, in <module>
with open(os.path.join("Users", "Kasutaja", "AppData", "Local", "Growtopia", "save.dat"), 'r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Kasutaja\\AppData\\Local\\Growtopia\\save.dat'
Process finished with exit code 1

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?
import pathlib
from shlex import quote
path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
f.write(content)
I'm getting this traceback
(tools) $ python test_filemake.py
Traceback (most recent call last):
File "test_filemake.py", line 13, in <module>
with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"
I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

Simple function won't run, beginner coder at work

I'm learning Python and it's early days for me. The following small bit of code won't run, the error message is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'logdata' is not defined
The file is called "logdata.py". The faulty(?) code is;
def logthis(addme):
f=open("log.txt", "a+")
f.write(addme)
f.close()
logthis('teststring')
If there is a better place for a basic question like this please let me know, I'm sure i'll have plenty more to come as i learn Python, thanks!
I think, you have some extra lines of code in beginning of file which uses undefined identifier (variable, function etc.) with name logdata. Something like this.
>>> def f():
... print(logdata)
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: name 'logdata' is not defined
>>>
If so, just define/initialize that. Finally, your code will work fine then as I have already tested it as follows.
>>> def logthis(addme):
... f = open("log.txt", "a+")
... f.write(addme)
... f.close()
...
>>> logthis('teststring')
>>>
>>> # Read the newly created file content
...
>>> f = open("log.txt", "r")
>>> f.read()
'teststring'
>>>

How to convert users input to file path in Python

I am currently trying to get the file_path (suppose ~/hello_world/) as user input and list all the files inside this directory. I can do this exact same thing if I pass ~/hello_world as sys.argv however, I can't seem to get it work if I take it as an input. I am trying to work the code from any directory and user inputted file path will be from /home/ubunut/...
Here's my working code as sys.argv:
This code is intended for unix based os only for now.
if len(sys.argv) == 2:
path = sys.argv[1]
files = os.listdir(path)
for name in files:
print(name)
Here's the code I am trying to work with:
path = input("file_path: ")
files = os.listdir(path)
for name in files:
print(name)
This is when it crashed with the following error:
Traceback (most recent call last):
File "test.py", line 14, in <module>
files = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '~/hello_world/'
Thanks in advance.
You need to expand the ~ like in the answer to this question
The following worked for me
import os
path = input("enter filepath: ")
for f in os.listdir(os.path.expanduser(path)):
print(f)

Resources