File or directory not found even though it exists - python

this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...

It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.

If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text

Related

Python adding a string leaves extra characters

If you need any more info just Let Me Know
I have a python script that adds a string after each line on a CSV file. the line file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()] is the trouble maker. For each file line it will add the string and then add a new line after each time the string is added.
Here is the script:
#Adding .JPG string to the end of each line for the Part Numbers
string_to_add = ".JPG"
#Open the file and join the .JPG to the current lines
with open("PartNums.csv", 'r') as f:
file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]
#Writes to the file until its done
with open("PartNums.csv", 'w') as f:
f.writelines(file_lines)
The script works and does what it is supposed to, however my issue is later on in this larger script. This script outputs into a CSV file and it looks like this:
X00TB0001.JPG
X01BJ0003.JPG
X01BJ0004.JPG
X01BJ0005.JPG
X01BJ0006.JPG
X01BJ0007.JPG
X01BJ0008.JPG
X01BJ0026.JPG
X01BJ0038.JPG
X01BJ0039.JPG
X01BJ0040.JPG
X01BJ0041.JPG
...
X01BJ0050.JPG
X01BJ0058.JPG
X01BJ0059.JPG
X01BJ0060.JPG
X01BJ0061.JPG
X01BJ0170.JPG
X01BJ0178.JPG
Without the \n in that line the csv file output looks like this file_lines = [''.join([x.strip(), string_to_add]) for x in f.readlines()]:
X00TB0001.JPGX01BJ0003.JPGX01BJ0004.JPGX01BJ0005.JPGX01BJ0006.JPG
The issue is when I go to read this file later and move files with it using this script:
#If the string matches a file name move it to a new directory
dst = r"xxx"
with open('PicsWeHave.txt') as my_file:
for filename in my_file:
src = os.path.join(XXX") # .strip() to avoid un-wanted white spaces
#shutil.copy(src, os.path.join(dst, filename.strip()))
shutil.copy(os.path.join(src, filename), os.path.join(dst, filename))
When I run this whole Script it works until it has to move the files I get this error:
FileNotFoundError: [Errno 2] No such file or directory: 'XXX\\X15SL0447.JPG\n'
I know the file exist however the '\n' should not be there and that's why I am asking how can I still get everything on a new line and not have \n after each name so when I move the file the strings match.
Thank You For Your Help!
As they said above you should use .strip():
shutil.copy(os.path.join(src, filename.strip()), os.path.join(dst, filename.strip()))
This way it gives you the file name or string you need and then it removes anything else.

Open and print the contents of a file?

I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided

Print in external files with FOR and getting blank txt files

In that part of code I make the files txt and its working
import sys
for i in range(6):
file = open('teste{:d}.txt'.format(i), 'a')
sys.stdout = file
And now the problem, the files were created but in this part of code it didnt work, i can compile but the files are empty
for i in range(1,6):
f=open('100K_Array_{:d}.txt'.format(i), 'r')
alist = f.readlines()
quickSort(alist)
print(alist)
f.close()
It appears to me that you haven't closed your output file properly. You should either use
with open('teste{:d}.txt', 'a') as file:
...
in which case with statement will handle closing the file for you. Otherwise you need to add file.close() to your current code.

Python ignores file type when creating file

I'm trying to create a .txt file with some data, and I want the file name to be the current time. But when I run my code it creates an empty file instead, without any file-type. Here is the code in question:
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as open_file:
# writing to file
It seems to ignore the ".txt" part because if i write the code like this it works just fine:
with open('filename.txt', 'w') as open_file:
It runs fine on my machine (Ubuntu 16.04 and python 3.5)
import datetime
import time
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as file:
file.write('code written')
please provide more info
And yes i am getting .txt in my file name
In windows, you cant use : in the filename. It stops the creation of the file when it reaches the colon.

python environment file open plus path

In environmental variables in system I have defined two variables:
A_home=C:\install\ahome
B_home=C:\install\bhome
following script is written to read information from location of variable A close it, then open location of variable B and write it there, thing is script only works with precise path e.g
C:\install\a\components\xxx\etc\static-data\myfile.xml
C:\install\b\components\xxx\etc\static-data\myfile.xml
problem is, that i need python to read path that is defined in env variable, plus common path like this: %a_home%\a\components\xxx\etc\static-data\myfile.xml`
so far i have this, and i cant move forward .... anyone have any ideas?? this script reads only exact path...
file = open('C:\install\a\components\xxx\etc\static-data\myfile.xml','r')
lines = file.readlines()
file.close()
file = open('C:\install\b\components\xxx\etc\static-data\myfile.xml','w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>XXX1</entity>\n')
file.write('<entity>XXX2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()
Try something like this:
import os
import os.path
home = os.getenv("A_HOME")
filepath = os.path.join(home, "components", "xxx", "etc", "static-data", "GenericEntityList.xml")
with open(filepath, 'r') as f:
for line in f:
print(line)
so finally success Thanks Tom, i was inspired by you ....
here goes
import os
path1 = os.environ['SOME_ENVIRO1']
path2 = os.environ['SOME_ENVIRO2']
file = open(path1 +'\\components\\xxx\etc\\static-data\\GenericEntityList.xml', 'r')
lines = file.readlines()
file.close()
file = open(path2 +'\\components\\xxx\\etc\\static-data\\GenericEntityList.xml', 'w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>ENTITY1</entity>\n')
file.write('<entity>ENTITY2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()

Categories