Home > Enterprise >  Read file and make a directory python
Read file and make a directory python

Time:06-13

The file names.txt contains a list of names. Each line contains one name.

Example:

  • Lisa
  • Luke
  • Marry

I'm trying to:

  • Create a directory for each name in the list if it doesn't exist already.

  • Furthermore, in each of those directories create a file with the name 15.txt.


with open("names.txt") as f:
for line in f:
    readnewline = f.read()
    name = []
    for name in readnewline:
        name = name.strip()
    if '.' not in name[-1]:
        directory = os.path.join(*([folder_path]   names))
        if not os.path.exists(directory):
            print('mk directory: {}'.format(directory))
            os.makedirs(directory)
    else:
        new_file = os.path.join(*([folder_path]   names))
        if not os.path.exists(new_file):
            with open(new_file, 'w'):
                print('write file: {}'.format(new_file))

CodePudding user response:

os.path.exists("path\to\file") checks if a path/file exists or not.

import os
with open("names.txt", "r") as fr:
    names = fr.readlines()
    fr.close()
    names = [name.strip() for name in names]

    # making directory for each name if not exist
    for name in names:
        if not os.path.exists(name):
            os.makedirs(name)

        # making a file in each directory
        file_name = "15.txt"  # file name

        with open(os.path.join(name, file_name), "w") as fw:
            fw.write("Some Data")
            fw.close()

CodePudding user response:

The pattern for making directories and writing files to them is:

 import os

 dirname = 'somedir'
 filename = 'somefile.txt'
 
 try:
     os.mkdir(dirname)
 except OSError:
     pass

 fullname = os.path.join(dirname, filename)
 with open(fullname, 'w') as f:
     f.write('some data')

This should get you started with what appears to be a homework problem.

  • Related