I'm looking to make a file that when you enter a directory, it creates a folder inside that directory. I'm using a batch file to create the folder, so I'm making it when you enter the directory, it will write that directory to the batch file, then run it. However I'm having some errors. Here's my code
directory = str(input())
text = 'cd ' + directory
lines = open('new.bat', 'r').readlines()
lines[2] = text
out = open('new.bat', 'w')
out.writelines(lines)
out.close()
call('new.bat')
out.close() exits my python script before it can have a chance to call 'new.bat', however if I move the out.close() to after it calls new.bat, it gives me an error that the file is currently being used. How do I fix this?
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 trying to draw a cube from the co-ordinates stored in text file it's working just fine when I'm executing it in vs code but my blender text editor keeps giving me 'No such file or directory' error
with open("list.txt", "r") as filestream:
for line in filestream:
currentline = line.split(",")
total = str( int(currentline[0]) + int(currentline[1]) + int(currentline[2])) + "\n"
print(currentline)[enter image description here][1]
Just provide the absolute path to the txt file, because blender python shell may not have its working directory in the directory containing the txt file.
EDIT
You could try to import the os module and call os.chdir("/directory/containing/the/txt/file/") before opening the txt file.
I created a .exe file with Pyinstaller. The program should create a data file with the results at runtime. It works in the Python interpreter mode when I execute python test.py but it doesn't work in the .exe mode. It simply doesn't create a file and responds with an error.
Which flags should I add to the command python -m PyInstaller --hidden-import=timeit --hidden-import=bisect -F test.py to make it work?
The exception with this setup is:
Error: [Errno 2] No such file or directory: "C:\Users\Admin\AppData\Local\Temp\..."
Where the aforementioned directory is temporary and I don't have access to it.
The piece of code which is supposed to write a file is:
def write_file(data, path, encoding='utf-8'):
'''Creates report files.'''
try:
if config.python_version == 2 and type(data) in (list, str):
f = io.open(path, 'wb')
else:
f = io.open(path, 'w', encoding=encoding, newline='')
if type(data) is list:
writer = csv.writer(f)
writer.writerows(data)
else:
f.write(data)
f.close()
console(u'Report file: ' + path)
except IOError as e:
console(e, level=Level.error)
I assume there should be a setting to point to the place where the file should be saved.
I've checked here https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-files-to-the-bundle but without success. I couldn't use the listed flags properly, nothing seemed to work.
How can I specify the place where the file would be saved?
The issue isn't with pyinstaller, it's with however you're creating your file.
You may be using some environment variable when running your python script from the command line that isn't set when you run your Exe
I have created a simple example of a program that creates a data file in the directory from which it is called:
#myscript.py
f = open("Test.txt", "w")
print("Hello World!", file=f)
Then I generate the Exe with Pyinstaller:
pyinstaller -F myscript.py
Copy the exe anywhere and you can create Test.txt, if you have permissions in that folder.
Double click myscript.exe
Test.txt appears in the same folder as myscript.exe
Hello World!
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.
Is there any way for me to read file that I saved inside a text file using python?
For example I have a file called filenames.txt. The content of the file should have name of other files such as:
/home/ikhwan/acespc.c
/home/ikhwan/trloc.cpp
/home/ikhwan/Makefile.sh
/home/ikhwan/Readme.txt
So, theoretically what I want to do is I have a Python script to change some header of the file. So filenames.txt will act as a platform for me whenever I want to run the script to change only selected file. The reason is I have so many files inside directory and subdirectories and I just want python to read only the files that I put inside filenames.txt and only change that particular file. In the future, if I want to run the script on other files, I just can add or replace filenames in filenames.txt
So the flow of the script will be as follows:
Run script-->script start search for the filenames inside filenames.txt-->script will add or change header of the file.
Current, i used os.walk but it will search within all directory and subdirectory. Here are my current function.
def read_file(file):
skip = 0
headStart = None
headEnd = None
yearsLine = None
haveLicense = False
extension = os.path.splitext(file)[1]
logging.debug("File extension is %s",extension)
type = ext2type.get(extension)
logging.debug("Type for this file is %s",type)
if not type:
return None
settings = typeSettings.get(type)
with open(file,'r') as f:
lines = f.readlines()
You don't need to walk through the file system if you already have your file paths listed in the filenames.txt, just open it, read it line by line and then process each file path from it, e.g.
# this is your method that will be called with each file path from the filenames.txt
def process_file(path):
# do whatever you want with `path` in terms of processing
# let's just print it to STDOUT as an example
with open(path, "r") as f:
print(f.read())
with open("filenames.txt", "r") as f: # open filenames.txt for reading
for line in f: # read filenames.txt line by line
process_file(line.rstrip()) # send the path stored on the line to process_file()