How to make python read all files in directory for a dictionary?

python create file in directory
how to give file path in python
python list all files in directory and subdirectories
python loop through files in directory recursively
python list files in directory
python loop through csv files in directory
read multiple files in python
python open file in directory

I have a collection of 20 text files in a folder that I am trying to create a dictionary for and output the dictionary to a text file.

I created a code that works for a single file in the directory by inputting a filename. However it doesn't let me input multiple text files at once, and if I run each one individually they just overwrite each other. I tried converting the file input to using import os and read from my cwd, but I'm running into errors with variables and I'm just not sure what I'm doing wrong.

fname = input ('Enter File: ')
hand = open(fname)

di = dict()
for lin in hand:
    lin = lin.rstrip()
    wds = lin.split()
    for w in wds:


        di[w] = di.get(w,0) + 1

print(di)


largest = -1
theword = None
for k,v in di.items() : 
    if v > largest : 
        largest = v
        theword = k

print(theword,largest)

f = open("output.txt", "w")
f.write(str(di))
f.close()

I tried adding

import os
for filename in os.listdir(os.getcwd()):
    fname = ('*.txt')
    hand = open(fname)

To the top, but I'm erroring out as it's not recognizing what I thought would be a wildcard to assign fname as the file it is reading.

You can loop through each and every .txt file inside your directory and print or store the content of those text files in a dictionary or variable.

import os

for filename in os.listdir(os.getcwd()):
         name, file_extension = os.path.splitext(filename)
         if '.txt' in file_extension:
                hand = open(filename)
                for line in hand:
                    print line

How to iterate over files in directory python, Example: print out all paths to files that have jpg or png extension in Both os. listdir() and os.scandir approaches only list the directories or files� Python List All Files in a Directory. Here, we are demonstrating functions that help traverse the file system and search for the files present. Os.walk() method. It gathers the file names present in a directory by traversing the dir in either top-down or bottom-up. It returns a tuple of the following three: Root: Gets only the folders from the input.

If you are using Python 3.4 or higher, your code can be very simplified by using pathlib.Path() and collections.Counter():

from pathlib import Path
from collections import Counter

counter = Counter()
dir = Path('dir')
out_file = Path('output.txt')

for file in dir.glob('*.txt'):
    with file.open('r', encoding='utf-8') as f:
        for l in f:
            counter.update(l.strip().split())

counter.most_common(10)

with out_file.open('w', encoding='utf-8') as f:
    f.write(counter)

If you are on Python 3.5 or higher, that code can be even more simple:

from pathlib import Path
from collections import Counter

counter = Counter()
dir = Path('dir')
out_file = Path('output.txt')

for file in dir.glob('*.txt'):
    counter.update(file.read_text(encoding='utf-8').split())

counter.most_common(10)
out_file.write_text(counter, encoding='utf-8')

And here is as sample output:

>>> from pathlib import Path
>>> from collections import Counter
>>> counter = Counter()
>>> file = Path('t.txt')
>>> file.is_file()
True
>>> with file.open('r', encoding='utf-8') as f:
...     for l in f:
...             counter.update(l.strip().split())
... 
>>> counter.most_common(5)
[('is', 10), ('better', 8), ('than', 8), ('to', 5), ('the', 5)]
>>> 

Python List Files in a Directory: Step-By-Step Guide, You can use the os. listdir() method to do this. You can also use the os. walk() method, which lists all files and folders within a directory, including files and folders within subdirectories. Python’s os module provides a function to get the list of files or folder in a directory i.e. os.listdir(path='.') os.listdir (path='.') os.listdir (path='.') It returns a list of all the files and sub directories in the given path.

If you want to use wildcards, you need the glob module. But in your case it sounds like you just want all files in one directory, so:

for filename in os.listdir('.'): # . is cwd
    hand = open(filename)

how to get the paths of all files in a dictionary python Code Example, Get code examples like "how to get the paths of all files in a dictionary python" instantly right from your google search directory in the tree rooted at directory top (including top itself), file_paths = [] # List which will store all of the full filepaths. The dump () method takes the Python dictionary as the first, and a File object as the second parameter. Once the above code executes, a file named store_file.yaml will be created in your current working directory.

import glob

# a list of all txt file in the current dir
files = glob.glob("*.txt")

# the dictionary that will hold the file names (key) and content (value)
dic = {}
# loop to opend files
for file in files:
    with open(file, 'r', encoding='utf-8') as read:
        # the key will hold the name the value the content
        dic[file] = read.read()
        # For each file we will append the name and the content in output.txt
        with open("output.txt", "a", encoding = 'utf-8') as output:
            output.write(dic[file] + "\n" + read.read() + "\n\n")

Chapter 8 – Reading and Writing Files, In this chapter, you will learn how to use Python to create, read, and save files on the hard drive. The C:\ part of the path is the root folder, which contains all other folders. You can make changes to the shelf value as if it were a dictionary. The following is the python code to display all the files and directories based on the passed absolute or relative path. If path is not specified in the calling statement then the contents of current working directory will be displayed.

Python Tutorial: Traversing directories recursively, The dirnames is a list of the names of the subdirectories in dirpath (excluding '. To get a full path (which begins with top) to a file or directory in dirpath, do� You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2. There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Chapter 11: Files and exceptions, To open a file, you specify its name and indicate whether you want to read or To test this function, we'll create a small dictionary and print the contents: Similarly, when you open a file for reading, Python looks for it in the current directory. The open() function opens and returns a file handle that can be used to read or write a file in the usual way. The code f = open('name', 'r') opens the file into the variable f, ready for reading

How to Get List of all Files in Directory and Sub , To get the list of all files in a folder/directory and its sub-folders/sub-directories, we will use os.walk() function. The os.walk() function yields an iterator over the� Python: How to create a zip archive from multiple files or Directory; Python : How to remove a file if exists and handle errors | os.remove() | os.ulink() Python : How to copy files from one location to another using shutil.copy() Python : How to delete a directory recursively using shutil.rmtree() Python : How to Get the current working

Comments
  • It seems you are counting words in files and calculating their frequencies. That's a perfect case use for collections.Counter.