Opening a file and creating a new file in the same folder - python

def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()
I need to create a new file called outputF and it should show up in the same folder that the inF is in, the problem is that it doesn't appear in the folder and I searched for the file on my computer but didn't find it

Get the Path:
import os
path= os.path.abspath("C:/example/cwd/mydir/myfile.txt")
open new file in path and write to it

Because the current working directory isn't the directory of the input file. Use os.getcwd() to get the current working directory, if it doesnt't match the directory of the input file, then you need to change your working directory first:
import os
def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
#change the working directory
os.chdir("C:\\Users\\Dell\\Desktop\\FF1")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()

Related

Open a file in python from 2 directory back

I want to read a file from 2 folders back..
with open('../../test.txt', 'r') as file:
lines = file.readlines()
file.close()
I want to read from ../../ two folders back. but not work..
How i can do that ?
Opening files in python is relative to the current working directory. This means you would have to change cd to the directory where this python file is located.
If you want a more robust solution:
To be able to run this from any directory, there is a simple trick:
import os
PATH = os.path.join(os.path.dirname(__file__), '../../test.txt')
with open(PATH, 'r') as file:
lines = file.readlines()
file.close()

Archiving Files Using Python Apart from Latest File

I am trying to archive existing file apart from the latest modified file in Python or FME. I have managed to get it to point where I can get python pick up the latest modified file but any ideas on how I can archive all the files i have in my folder apart from the last modified file?
Thank You
You can solve your problem using this snippet of code:
import glob
import os
import zipfile
files_dir = r'C:\Users\..\files' # here should be path to directory with your files
files = glob.glob(files_dir + '\*')
# find all files that located in specified directory
files_modify_dt = [os.path.getmtime(file) for file in files]
# take files except last modified file
files_to_zip = [file for _, file in sorted(zip(files_modify_dt, files))][:-1]
# zip of selected files
with zipfile.ZipFile(os.path.join(files_dir, 'archive.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_obj:
for file in files_to_zip:
zip_obj.write(file, os.path.basename(file))
os.remove(file)

How to add directory or make directory to current path and use file

I want to make a directory on current path and add an excel file in that path and use that excel file in script....please help
currently I am doing
my_excel_file = Path(sys.argv[2])
if not my_excel_file.is_file():
print ("Excel File not exist")
logging.error("Excel File not exist")
exit(-2)
but i want to add directory '/tmp/old excel/n.xlsx' in current path and use n.xlsx file
This code will create a directory and file if does not exist. You can also write to that file :
import os
filename = "tmp/old excel/n.xlsx"
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, "w") as f:
f.write("content")

Editing file names and saving to new directory in python

I would like to edit the file name of several files in a list of folders and export the entire file to a new folder. While I was able to rename the file okay, the contents of the file didn't migrate over. I think I wrote my code to just create a new empty file rather than edit the old one and move it over to a new directory. I feel that the fix should be easy, and that I am missing a couple of important lines of code. Below is what I have so far:
import libraries
import os
import glob
import re
directory
directory = glob.glob('Z:/Stuff/J/extractions/test/*.fsa')
The two files in the directory look like this when printed out
Z:/Stuff/J/extractions/test\c2_D10.fsa
Z:/Stuff/J/extractions/test\c3_E10.fsa
for fn in directory:
print fn
this script was designed to manipulate the file name and export the manipulated file to a another folder
for fn in directory:
output_directory = 'Z:/Stuff/J/extractions/test2'
value = os.path.splitext(os.path.basename(fn))[0]
matchObj = re.match('(.*)_(.*)', value, re.M|re.I)
new_fn = fn.replace(str(matchObj.group(0)), str(matchObj.group(2)) + "_" + str(matchObj.group(1)))
base = os.path.basename(new_fn)
v = open(os.path.join(output_directory, base), 'wb')
v.close()
My end result is the following:
Z:/Stuff/J/extractions/test2\D10_c2.fsa
Z:/Stuff/J/extractions/test2\E10_c3.fsa
But like I said the files are empty (0 kb) in the output_directory
As Stefan mentioned:
import shutil
and replace:
v = open(os.path.join(output_directory, base), 'wb')
v.close()
with:
shutil.copyfile (fn, os.path.join(output_directory, base))
If I'am not wrong, you are only opening the file and then you are immediately closing it again?
With out any writing to the file it is surely empty.
Have a look here:
http://docs.python.org/2/library/shutil.html
shutil.copyfile(src, dst) ;)

Where do I store text files for Python

Which folder location do I store text files on my computer for python to access? I'm trying to open a file called word.txt with the command fin = open('words.txt').
You need to use the full path to the file.
with open('/path/to/words.txt', 'r') as handle:
print handle.read()
Otherwise, it will be using your current directory.
import os
# Print your current directory
print os.path.abspath(os.curdir)

Categories