I'm trying to read in a .txt file on chromebook to manipulate the data that is there. My code to source the file is:
def readInFile():
arr_intValues = []
myFile = open("#MY FILE HERE", "r")
#you need to change the directory
for myLine in myFile:
arr_intValues.append(int(myLine))
return arr_intValues
myNewList = readInFile()
print(myNewList)
Trouble is, i cannot find out where the source of the file is for this code. If i drop the file into a chrome tab, it reads:
file:///media/fuse/crostini_9549350604ce9beeb7d5a9a66d5bf09733144d34_termina_penguin/RandomNum.txt
Meanwhile the file location that "Get info" returns is:
My files/Linux files/RandomNum.txt
Both of these options fail if I attempt to open it and print it in my code.
How do I find the correct file directory?
I attempted to find the directory of a .txt file on using Chrome OS and have not been successful.
If you're running the program on Linux, you'll need to specify the Linux path.
Related
I am getting that error for my program with my sys.argv[1] file. The specific csv file i am importing is there i can see it and open it myself.
myfile = open("sys.argv[1]", "r")
reader = csv.DictReader(myfile)
dnalist = list()
for dictionary in reader:
dnalist.appeand(dictionary)
It cant seem to find the file I input into my command line. I double checked that I am in the correct folder and spell the name of the subfolder correctly and the file name.
I'm learning Python (with Python Crash Course book) and i'm currently working with climate data from the NOAA, but everytime i try to import a file, Python does not find it. I had this error for other programs too and i can't really solve it. Could anyone help me please ?
Here's my code :
import csv
filename = 'new-york-weather_60-20.csv'
try :
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
print(header_row)
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
The Python interpreter assumes that the file 'new-york-weather_60-20.csv' is in the same directory (folder) as where python currently 'is', i.e., the current working directory.
You can see the current working directory by using the os module.
import os
print(os.getcwd())
This should be the path in which the csv file is located. If it is not, you can either move the file into that same location, or you can move the current working directory to the path where the file is located
import os
os.chdir('/the/location/on/your/computer/wherethefileislocated')
filename = 'new-york-weather_60-20.csv'
# You can check if the file is located in this directory
if os.path.exists(filename): # only if this file exists in this location do we continue
print('The file exists!')
with open(filename) as f:
# your code goes here
else:
print('The file does not exist in this directory')
I am trying to read content of a file on my work network from my work network. I copy and pasted a code snippet from a google search and modified it to the below. Why might I still be getting [Errno 2] (I have changed some of the path names for this question board)
The file path in my file explorer shows that "> This PC > word common common" and I don't have "This PC" in my path. I tried adding that into the place I would think it goes in the string. That didn't solve it.
I tried making sure I have matching capitalization. That didn't solve it.
I tried renaming the file to have a *.txt on the end. That didn't solve it.
I tried the different variations of // and / and \ with and without the r predecessor and while that did eliminate the first error I was getting. It didn't help this error.
(Looking at the code errors in the right gutter is says my line length is greater than the PEP8 standard. While I doubt that is the root of my problem, if you can throw in the 'right' wrap method for a file path that long that would be helpful.)
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
Full Error Copy:
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py", line 1, in
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
FileNotFoundError: [Errno 2] No such file or directory: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
EDIT
DEBUG EFFORTS
working to figure out how to change directory. Just in case that is the problem. Tested this code bit
import os
path = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
Received this error
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py", line 5, in <module>
os.chdir(path)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
My intention for adding the picture below is to show how File Explorer displays the file path for my file
FileExplorerPathScreenShot
EDIT
I think this confirms that my 'OS' doesn't have my file.
from os import path
path.exists("PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246")
def main():
print ("File exists:" + str(path.exists('PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246')))
if __name__== "__main__":
main()
Output
File exists: False
I thought OS was a standard variable for Operating system. Now I'm not sure.
EDIT
Using Cmd in DOS, I confirmed that my path for the z: is correct
EDIT - Success
I ran
import os
print( os.listdir("z:/"))
Confirmed I don't need the monster string of folders.
Confirmed, although explorer doesn't show it, it is a *.txt file
Once I implemented these two items the first code worked fine.
Thank you #Furas
To open and read a file specify the filename in your path:
myfile = open("U:/matrix_neo/word common common/hello world.txt", "rt") # open file
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
The U: is a mapped drive in my network.
I did not find any issue with your change dir example. I used a path on my U: path again and it returned True.
import os
path = "U:/matrix_neo/word common common"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
The check the attributes on the directory that you are trying to read from. Also try to copy the file to a local drive for a test and see if you can read the file and also check if it exists.
This is an alternative to the above and uses your path to make sure that the long file path works:
import os
mypath = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
myfile = 'whatever is your filename.txt'
if not os.path.isdir(mypath):
os.makedirs (mypath)
file_path = os.path.join(mypath, myfile)
print(file_path)
if os.path.exists(file_path) is True:
with open(file_path) as filein:
contents = filein.read()
print(contents)
I tested this code using a long csv file.,Replace the variable myfile with whatever is your file name.
I am a python beginner and I try to build a script which consolidates all existing excel workbooks into a new one in the same folder... However I have an error stating that the excel files could not be found.... I am stuck. see below the coding :
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
path = r"/Users/lb/Desktop/consolidation"
suffix = "xlsx"
dirs = os.listdir(path)
for file in dirs:
if file.endswith(suffix):
w = excel.Workbooks.Open(file)
w.Sheets(1).Copy(wb.Sheets(1))
wb.SaveAs(os.path.join(path, "result.xlsx"))
excel.Application.Quit()
This is the error when I run the script :
File "C:/Users/lb/PycharmProjects/New Project/fusion2.py", line 12, in
w = excel.Workbooks.Open(file)
File "C:\Users\lb\AppData\Local\Temp\gen_py\3.7\00020813-0000-0000-C000-000000000046x0x1x7\Workbooks.py", line 78, in Open
, Converter, AddToMru, Local, CorruptLoad)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "'business_Descriptor.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.
If you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", 'xlmain11.chm', 0, -2146827284), None)
I believe your path may be wrong. Usually speaking, the users directory in Windows should go something like this:
C:\\Users\\lb\\Desktop\\consolidation
If you are unsure about your paths, you can also debug your path by navigating through it in your python script until you find your folder with the os.chdir() command, and os.listdir() command. When you're at the folder you want, you can then use the os.getcwd() command.
I also recommend this reading if you want to get familiar with filesystems in python.
Continuing on from the previous part, it seems that in your code,
for file in dirs:
if file.endswith(suffix):
w = excel.Workbooks.Open(file)
w.Sheets(1).Copy(wb.Sheets(1))
You're trying to open the file with the string name of the file itself, not the path. If you take a look at the snippet below from this link you'll see that they append the name with the path directory. This should fix your issue :P
import os
for filename in os.listdir('path/to/dir'):
if filename.endswith('.log'):
with open(os.path.join('path/to/dir', filename)) as f:
content = f.read()
Essentially what you need to do is change your
w = excel.Workbooks.Open(file)->
w = excel.Workbooks.Open(os.path.join(path,file))
So the final result of that part of your code should look like this (Note the indentations at the if! Without them the if statement does nothing):
for file in dirs:
if file.endswith(suffix):
w = excel.Workbooks.Open(os.path.join(path,file))
w.Sheets(1).Copy(wb.Sheets(1))
I am trying to set up GPT-2 encoding using the following tutorial:
https://medium.com/#ngwaifoong92/beginners-guide-to-retrain-gpt-2-117m-to-generate-custom-text-content-8bb5363d8b7f
I am trying to enter
python encode.py giselle.txt giselle.npz
in the command prompt but it keeps giving me a FileNotFoundError for an encoder.json file that is already in the path it tries to retrieve it from.
How may I go about fixing this?
I have tried editing the encode.py file to specify the exact path to the encoder.json file but it still gives FileNotFoundError
def get_encoder(model_name):
with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
encoder = json.load(f)
with open(os.path.join('models', model_name, 'vocab.bpe'), 'r', encoding="utf-8") as f:
bpe_data = f.read()
I expected the giselle.txt to be encoded to the giselle.npz file but all that is sent in the command prompt is
File "C:\projectgiselle\gpt-2-finetuning\src\encoder.py", line 109, in get_encoder
with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'models\\117M\\encoder.json'
I had this same error!
The tutorial is geared towards Windows users and has you copy train.py and encode.py into the /src/ directory for 'simplicity', so that you don't have to modify the PYTHONPATH. But moving these might violate the code's expectations of where certain scripts are. The solution is simply to move the expect files (encoder.json) correspondingly.
I was able to successfully continue the tutorial by copying and pasting the entire /model/ folder into /src/, so that /src/model/. Then you can run encode.py from /src/ as it instructs.