I am trying to compare the contents of a directory to a text file.I have certain files in the directory and I also want to compare the files to this text file. How do I achieve this?
To get the directory's content (list of filenames):
import os
dir_content = os.listdir(directory_path)
To get a text-files content (line by line in a list):
with open(filename) as f:
lines = f.readlines()
Related
I want to write in all the files within a directory based on their extensions. I can write to a specific file but my goal is code that can write to all the *.txt files that are in a specific directory. With the following code I can list all text files and search for a file but as a beginner in Python I don't know how to write a sentence in all the *.txt files.
import glob
import os
directory=os.listdir(r'C:\Users\Lenovo\Desktop\z')
myfiles=glob.glob('*.txt')
print(myfiles)
def find_files(filename, search_path):
result= []
for root, dir, files in os.walk(search_path):
if filename in files:
result.append(os.path.join(root, filename))
return result
print(find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z"))
In your example you should be able to just do the following:
textfiles = find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z")
for textfile in textfiles: # go over each file that it found
with open(textfile, "a") as f: # open the textfile in mode append (hence the a) and have it be assigned to f
f.write("a") # then write "a" to the file.
To do all of them:
for textfile in os.listdir():
if textfile.endswith(".txt"):
with open(textfile, "a") as f:
f.write("a")
I have a list of file names I am trying to iterate over each file and use a with open statement.
#list of text files
files = ['file1.txt','file2.txt','file3.txt']
for file in files:
with open(file as f ):
file.readlines()
This should work. Note that I used os.chdir() to change the working directory to the directory containing the files. If you files List contain the full path of the files, then you won't need to do this.
import os
#change working directory to the directory containing the files
os.chdir("C:\\Folder1\\Folder Containing files")
files = ['file1.txt','file2.txt','file3.txt']
content = []
for file in files:
with open(file, 'r') as f:
content.append(f.readlines()) # note that it's f.readlines() and not file.readlines()
with open(file as f ) should be changed to with open(file, 'r') as f. This specifies we want to open the file object in read mode and store this file object in read mode as the variable f.
You should also replace file.readlines() f.readlines() as file is the string of the file path rather than the file object itself.
So I want to loop through a directory of text files (.txt) and print the output(names of all txt files) in a separate file using json.dump?
So far i only have:
data = #name of txt files in directory
with open('file.txt','w') as ofile:
json.dump(data,ofile)
You can write this code, assuming your directory is the current directory (.)
import os
import json
directory_path = '.' #Assuming your directory path is the one your script lives in.
txt_filenames = [fname for fname in os.listdir(directory_path) if fname.endswith('.txt')]
with open('file.txt', 'w') as ofile:
ofile.write(json.dumps({
'filenames': txt_filenames
}))
So, your output file (in this case file.txt) will look like this:
"filenames": ["a.txt", "b.txt", "c.txt"]}
Hope it helps,
I would like to read the all the files in a directory so I'm doing the following:
path = '/thepath/of/the/files/*'
files = glob.glob(path)
for file in files:
print file
The problem is that when I print the files I don't obtain anything; any idea of how to return all the content of the files in a list per file?
EDIT: I appended the path with an asterisk, this should give you all the files and directories in that path.
Like in the comment I posted some time ago, this should work:
contents=[open(ii).read() for ii in glob.glob(path)]
or this, if you want a dictionary instead:
contents={ii : open(ii).read() for ii in glob.glob(path)}
I would do something like the following to only get files.
import os
import glob
path = '/thepath/of/the/files/*'
files=glob.glob(path)
for file in files:
if os.path.isfile(file):
print file
Your question is kind of unclear, but as I understand it, you'd like to get the contents of all the files in the directory. Try this:
# ...
contents = {}
for file in files:
with open(file) as f:
contents[file] = f.readlines()
print contents
This creates a dict where the key is the file name, and the value is the contents of the file.
I need to search in a parent folder all files that are config.xml
and in those files replace one string in another. (from this-is to where-as)
import os
parent_folder_path = 'somepath/parent_folder'
for eachFile in os.listdir(parent_folder_path):
if eachFile.endswith('.xml'):
newfilePath = parent_folder_path+'/'+eachFile
file = open(newfilePath, 'r')
xml = file.read()
file.close()
xml = xml.replace('thing to replace', 'with content')
file = open(newfilePath, 'w')
file.write(str(xml))
file.close()
Hope this is what you are looking for.
You want to take a look at os.walk() for recursively traveling through a folder and subfolders.
Then, you can read each line (for line in myfile: ...) and do a replacement (line = line.replace(old, new)) and save the line back to a temporary file (tmp.write(line)), and finally copy the temp file over the original.