I'm trying to take the input file and save it into a new folder on my computer, but I can't figure out how to do it correctly.
Here is the code I tried:
from os.path import join as pjoin
a = raw_input("File Name: ")
filepath = "C:\Documents and Settings\User\My Documents\'a'"
fout = open(filepath, "w")
path_to_file = pjoin("C:\Documents and Settings User\My Documents\Dropbox",'a')
FILE = open(path_to_file, "w")
When I run it, it's putting two \ in between each sub-directory instead of one and it's telling me it's not an existing file or directory.
I am sure there is an easier way to do this, please help.
Why do you have unescaped "'quotes_like_this_inside_quotes'"? That may be a reason for that failure.
From what I can understand, the directories you are saving to are "C:\Documents and Settings\User\My Documents\' and 'C:\Documents and Settings\User\My Documents\'.
Whenever you are messing with directories/paths ALWAYS use os.expanduser('~/something/blah').
Try this:
from os.path import expanduser, join
path_to_file1 = join(expanduser('~/Dropbox/'), 'a')
path_to_file2 = join(expanduser('~'), 'a')
fout = open(path_to_file2, "w")
FILE = open(path_to_file1, "w")
And the double-backslashes are OK, AFAIK.
Let me know if this works - I'm not on a Windows box at the moment.
Related
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()
I tried using open but it gives an error that the folder doesn't exist, which makes no sense since this is a command to create a folder, not read one. I saw Automatically creating directories with file output, but there is an error saying this is a Errno 30: Read only system: "/folder". Does anyone know how to avoid Error 30?
My code so far:
import os
filename = "/folder/y.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
I figured i just shouldn't put the slash behind the "folder"filename = "folder/y.txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f: f.write("FOOBAR")
If I want to read files named "ABCbook.txt" under directors A/B/C, which means the path A/B/C depends on the files' name and the folders A/B/C are hierarchical. How can I achieve it in Python?
We will use os.path.join to make the file path in a platform-independent way, then open the file using the normal with open... technique.
import os
my_file = os.path.join('A', 'B', 'C', 'ABCbook.txt')
with open(my_file) as f:
# your code to work on the file goes here
for line in f:
print(line)
import os
filename = "ABCbook.txt"
path = list(filename[:3]) + [filename]
syspath = os.path.join(*path)
print(syspath)
output (on windows):
A\B\C\ABCbook.txt
on linux or mac it will return
A/B/C/ABCbook.txt
I'd like to read the contents of every file in a folder/directory and then print them at the end (I eventually want to pick out bits and pieces from the individual files and put them in a separate document)
So far I have this code
import os
path = 'results/'
fileList = os.listdir(path)
for i in fileList:
file = open(os.path.join('results/'+ i), 'r')
allLines = file.readlines()
print(allLines)
at the end I dont get any errors but it only prints the contents of the last file in my folder in a series of strings and I want to make sure its reading every file so I can then access the data I want from each file. I've looked online and I cant find where I'm going wrong. Is there any way of making sure the loop is iterating over all my files and reading all of them?
also i get the same result when I use
file = open(os.path.join('results/',i), 'r')
in the 5th line
Please help I'm so lost
Thanks!!
Separate the different functions of the thing you want to do.
Use generators wherever possible. Especially if there are a lot of files or large files
Imports
from pathlib import Path
import sys
Deciding which files to process:
source_dir = Path('results/')
files = source_dir.iterdir()
[Optional] Filter files
For example, if you only need files with extension .ext
files = source_dir.glob('*.ext')
Process files
def process_files(files):
for file in files:
with file.open('r') as file_handle :
for line in file_handle:
# do your thing
yield line
Save the lines you want to keep
def save_lines(lines, output_file=sys.std_out):
for line in lines:
output_file.write(line)
you forgot indentation at this line allLines = file.readlines()
and maybe you can try that :
import os
allLines = []
path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ i), 'r')
allLines.append(file.read())
print(allLines)
You forgot to indent this line allLines.append(file.read()).
Because it was outside the loop, it only appended the file variable to the list after the for loop was finished. So it only appended the last value of the file variable that remained after the loop. Also, you should not use readlines() in this way. Just use read() instead;
import os
allLines = []
path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ i), 'r')
allLines.append(file.read())
print(allLines)
This also creates a file containing all the files you wanted to print.
rootdir= your folder, like 'C:\\Users\\you\\folder\\'
import os
f = open('final_file.txt', 'a')
for root, dirs, files in os.walk(rootdir):
for filename in files:
data = open(full_name).read()
f.write(data + "\n")
f.close()
This is a similar case, with more features: Copying selected lines from files in different directories to another file
Brand new to Python, first time poster, be easy on me please!
I would like to insert a line of text into all files of a specific extension (in the example, .mod) within the current folder. It can point to a specific folder if that is easier.
Below is something that I copied and modified, it is doing exactly what I need for one specific file, the part about replacing sit with SIT is completely unnecessary, but if I remove it the program doesn't work. I have no idea why that is, but I can live with that.
import sys, fileinput
for i, line in enumerate(fileinput.input('filename.mod', inplace=1)):
sys.stdout.write(line.replace('sit', 'SIT'))
if i == 30: sys.stdout.write('TextToInsertIntoLine32' '\n') #adds new line and text to line 32
My question is, how do I run this for all files in a directory? I have tried replacing the filename with sys.argv[1] and calling the script from the command line with '*.mod' which did not work for me. Any help would be appreciated.
You can do like this:
import os
folder = '...' # your directory
files = [f for f in os.listdir(folder) if f.endswith('.mod')]
Then you can get a list of files with the extension '.mod', you can run your function for all files.
You could use glob.glob to list all the files in the current working directory whose filename ends with .mod:
import fileinput
import glob
import sys
for line in fileinput.input(glob.glob('*.mod'), inplace=True):
sys.stdout.write(line.replace('sit', 'SIT'))
if fileinput.filelineno() == 32:
#adds new line and text to line 32
sys.stdout.write('TextToInsertIntoLine32' '\n')
You can use os.walk function:
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".mod"):
filepath = os.path.join(root, file)
with open(filepath, 'r', encoding='utf-8') as f:
text = f.read()
print('%s read' % filepath)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(text.replace('sit', 'SIT'))
print('%s updated' % filepath)
Easy: you don't have to specify a filename. fileinput will take the filenams from sys.argv by default. You don't even have to use enumerate, as fileinput numbers the lines in each file:
import sys, fileinput
for line in fileinput.input(inplace=True):
sys.stdout.write(line.replace('sit', 'SIT'))
if fileinput.filelineno() == 30:
sys.stdout.write('TextToInsertIntoLine32' '\n')