I've searched for a while for the solution, so I won't bother you, but I can't find it for my problem.
I want to copy text from .txt file and paste it to another one. The problem is, I've got a bunch of these files.
I've tried to do this in python, as I have the previous script to add a new line to .txt file based on the folder name, but I just can't figure it myself.
So what I did so far based on research is:
import os
rootdir = 'FOLDERS'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file == 'opis.txt':
source = '%s.txt' % subdir
if os.path.exists(source):
target = os.path.join(subdir, file)
with open(source) as source_file:
with open(target, 'a') as target_file:
target_file.write(source_file.read())
In folder 'FOLDERS' I have .txt files that have a name as a folder containing "opis.txt" file (where I want to paste text from the text file with folder name), e.g.
\FOLDERS\P.1417.1969.11.txt
\FOLDERS\P.1417.1969.11\opis.txt
I want to copy the line starting with "R:" (or just whole file content, as this line is the only text there) from the P.1417.1969.11.txt file and paste it to P.1417.1969.11\opis.txt
I have hundreds of files and folders with corresponding names, that's why I need a script.
EDIT: I've changed the code to the one that works.
Related
I am trying to create part of a program that will take the values found in two CFG files and use them to determine what filetype to search for as well as what folder location to use. The code I found online sort of suits my needs, However I would like to not use a hard coded file path. Here is the code I have modified so far:
import glob
location = open("config.cfg", encoding = 'cp1252')
location = location.read()
filetype = open("filetype.cfg", encoding = 'cp1252')
filetype = filetype.read()
fileset = [file for file in glob.glob(location + filetype, recursive=True)]
print(location)
print(filetype)
for file in fileset:
print(file)
The config.cfg contains one line, which is the file path to a folder with 3 sample JPG files in it.
C:/test
The filetype.cfg contains one line as well, which is the file type to search for
"**/*.jpg"
I've gotten to the point where this code throws no errors, but it also doesn't work as intended either, it seems to read the files properly, but doesn't list the files in the folder. The Config.CFG file contains the folder path, i.e. C:/test, while the filetype.cfg contains "**/*.jpg", which is the type of file I would like searched for. I found the original code here: https://www.techbeamers.com/python-list-all-files-directory/, Look under the 'glob' method.
The original (fully working) code from the link above:
import glob
location = 'c:/test/temp/'
fileset = [file for file in glob.glob(location + "**/*.py", recursive=True)]
for file in fileset:
print(file)
Using Python 3.8 64bit on Windows 10.
Moved from an edit to the question by the OP to an answer.
Remove the quotes around "**/*.jpg" in the filetype.cfg file:
**/*.jpg
I am having issues reading the contents of the files I am trying to open due to the fact that python believes there is:
"No such file or directory: 'Filename.xrf'"
Here is an outline of my code and what I think the problem may be:
The user's input defines the path to where the files are.
direct = str(raw_input("Enter directory name where your data is: ))
path = "/Users/myname/Desktop/heasoft/XRF_data/%s/40_keV" \
%(direct)
print os.listdir(path)
# This lists the correct contents of the directory that I wanted it to.
So here I essentially let the user decide which directory they want to manipulate and then I choose one more directory path named "40_keV".
Within a defined function I use the OS module to navigate to the corresponding directory and then append every file within the 40_keV directory to a list, named dataFiles.
def Spectrumdivide():
dataFiles = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.xrf'):
dataFiles.append(file)
Here, the correct files were appended to the list 'dataFiles', but I think this may be where the problem is occurring. I'm not sure whether or not Python is adding the NAME of the file to my list instead of the actual file object.
The code breaks because python believes there is no such file or directory.
for filename in dataFiles:
print filename
f = open(filename,'r') # <- THE CODE BREAKS HERE
print "Opening file: " + filename
line_num = f.readlines()
Again, the correct file is printed from dataFiles[0] in the first iteration of the loop but then this common error is produced:
IOError: [Errno 2] No such file or directory: '40keV_1.xrf'
I'm using an Anaconda launcher to run Spyder (Python 2.7) and the files are text files containing two columns of equal length. The goal is to assign each column to a list and the manipulate them accordingly.
You need to append the path name not just the file's name using the os.path.join function.
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.xrf'):
dataFiles.append(os.path.join(root, file))
Is there a way to read all the unopened files in a folder only by passing the one specific file name that is present in that folder?I know to read all the files in a directory passing the directory name using os.walk.But in this specific problem I can just pass only one file name.Need your help for this problem.Thank you.
If I understand you correctly, you have a path of a single file, while you want to read all files in the folder it's located in.
You can achieve this easily:
dir_name, file_name = os.path.split(filepath)
for root, dirs, files in os.walk(dir_name):
for file in files:
with open(file) as f:
file_content = f.read()
I am pretty new to python.I have a directory and inside which I have 2 sub directory.Each sub directory contain 100 text file.I want to read the content of each file of the both the sub directory and put them in a single text file in such a way that each file content is in a single line in the new file.how can I achieve this in pyhon.thank you
Since you don't have anything.. you could try starting from here. You can use the glob module instead to load files from a single level of subdirectories, or use os.walk() to walk an arbitrary directory structure depending on your requirement,
To open say all text files in an arbitrary nesting of directories:
import os
import fnmatch
for dirpath, dirs, files in os.walk('Test'):
for filename in fnmatch.filter(files, '*.txt'):
with open(os.path.join(dirpath, filename)):
# deal with this file as next loop will present you with a new file.
#use the filename object to do whatever you want with that file
Since your new like you said. Watch out for the indentations. #Goodluck
Basically i'm trying to print all excel files in a directory. In one of the folders, i don't have a excel file named '~$EndManifold-4Slot.xlsm', but while printing the files, i see this is present, which is actually not there.
Could anyone suggest on how to improve the same?
def Fnfolders(rootdir):
xlFilesList=[]
for dirname, dirnames, filenames in os.walk(rootdir):
for file in os.listdir(dirname):
if '.xls' in file or '.xlsx' in file:
fullPath=os.path.join(dirname)+"\\"+file
xlFilesList.append(fullPath)
return xlFilesList
xlFilesList=Fnfolders(rootdir)
for excel in xlFilesList:
print (excel)
Normally, files like - ~$EndManifold-4Slot.xlsm are temporary files created when you openned your file in Excel. they are usually hidden, you can find them in your explorer if you enable Show Hidden Files in folder options.
You can read more about those temporary files here .