Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
using python 3.3
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
use open:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f
Related
Im new to Python so apologies if this is a basic question.
I have successfully created an exe file that writes to my specific desktop directory, but I am struggling to find a way to write to any users desktop directory.
The idea being my exe file can be copied onto any user profile and work the same.
Here is my code:
file = open('C:\\Users\\user\\Desktop\\PC info.txt','w')
Could somebody help me adjust my code to work on any users desktop. Thank you in advance
You can get the username with the os module:
import os
username = os.getlogin() # Fetch username
file = open(f'C:\\Users\\{username}\\Desktop\\PC info.txt','w')
file.write('Hello desktop')
file.close()
You could use os.getlogin with an f-string to insert the username to the file path:
import os
with open(fr'C:\Users\{os.getlogin()}\Desktop\PC info.txt', 'w') as f:
# do something with f
But, a much better cleaner way nowadays would be to use pathlib:
import pathlib
with open(pathlib.Path.home() / "Desktop/PC info.txt", "w"):
# do something with f
Also, it's always advisable to use a context manager (with open(...) as f) to handle files, so that the filehandler gets closed even if an exception occurs.
If you are using Python3.5+, you can use the following to get the path to the current user's home directory:
import os
import sys
from pathlib import Path
def main():
home = str(Path.home())
path = os.path.join(home, "filename.txt")
with open(path, "w") as f:
f.write("HelloWorld")
if __name__ == '__main__':
main()
Is this what you are looking for?
username = "MrShaun"
filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username)
file = open(filename, 'w')
In this example, filename would be: "C:\Users\MrShaun\Desktop\PC info.txt"
Obviously, you would probably want to build a structure around it, for example asking the user for input of a username and assigning that to the variable username.
Read more about formatting strings in Python here
I'm struggling with reading a file in python, the py file and CSV file are in the same folder but the VSCode makes an error and can't find the file:
import csv
with open('file.csv','r') as f:
reader = reader(f)
...
how can I fix this??
and the error is:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'file.csv'
If you run:
import os
os.getcwd()
You'll find out your current working directory which I assume is not the one you were expecting. If you're running the python script through VS code it could be using it could be the directory which you have open on the left hand side.
So either run the python using the correct working directory or use an absolute path like this:
import csv
with open('pathname/file.csv','r') as f:
reader = reader(f)
There might be an issue with your relative path settings.
Try this:
import os
import csv
dir = os.path.dirname(__file__)
filename = os.path.join(dir, 'file.csv')
with open(filename,'r') as f:
reader = reader(f)
Are you using spyder?
If so, please check if the current working path is the path your py file locates.
import csv
with open('file.csv','r') as f:
reader = csv.reader(f)
in this case your file.csv should be in folder where is your python script (current working folder)
or, instead of 'file.csv' you can put absolute path
When I make this code into an executable the function of writing a file works, but it writes to a random directory. I'm not sure how to get it to write to my desktop, like it did when it was a regular python file.
Here is my code,
def write():
print('Creating a new file')
name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'w') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Cannot tell what?')
sys.exit(0) # quit Python
You need to specify the path you want to save to. Furthermore, make use of os.path.join (documentation) to put the path and filename together. You can do something like this:
from os.path import join
def write():
print('Creating a new file')
path = "this/is/a/path/you/want/to/save/to"
name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(join(path, name),'w') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Cannot tell what?')
sys.exit(0) # quit Python
It is not writing into a random directory. It is writing into current directory, that is the directory you run it from. If you want it to write to a particular directory like your desktop you either need to add the path to the file name or switch the current directory. The first is done with
name = os.path.join('C:\Users\YourUser\Desktop', name)
the second is done with
os.chdir('C:\Users\YourUser\Desktop')
Or whatever the path to your desktop is.
I am trying to process every files inside a folder line by line. I need to check for a particular string and write into an excel sheet. Using my code, if i explicitly give the file name, the code will work. If I try to get all the files, then it throws an IOError. The code which I wrote is as below.
import os
def test_extract_programid():
folder = 'C://Work//Scripts//CMDC_Analysis//logs'
for filename in os.listdir(folder):
print filename
with open(filename, 'r') as fo:
strings = ("/uri")
<conditions>
for line in fo:
if strings in line:
<conditions>
I think the error is that the file is already opened when the for loop started but i am not sure. printing the file name prints the file name correctly.
The error shown is IOError: [Errno 2] No such file or directory:
if your working directory is not the same as folder, then you need to give open the path the the file as well:
with open(folder+'/'+filename, 'r') as fo
Alternatively, you can use glob
import glob
for filename in glob.glob(folder+'/*'):
print filename
It can't open the path. You should do
for filename in os.listdir(folder):
print folder+os.sep()+filename
I am running a script that would change the contents inside a file with extension hgx.
E.g. test.hgx
Now, I have multiple files with extension hgx and I would like to run this same script for all the files (with extension hgx).
My current script looks like:
file_name = "test.hgx"
x = open(file_name,'r')
....(and so on)
Is it possible to use something like:
file_name = "*.hgx"
x = open(file_name,'r')
....
So that the script runs for all the files with extension hgx. Any workaround or method to do this?
Use glob.iglob():
for filename in glob.iglob("*.hgx"):
with open(filename) as f:
# process file f here