-5

How do I read a file in Python and write its contents to another file with the following condition:

If the character is a letter in the input file, then the letter should be made lowercase and written to the output file. Other characters should not be written.

def lower_case():

    file_name = input("Enter the file name to read from: ")
    tmp_read = open(str(file_name), 'r')
    tmp_read.readline()

    fileName = input("Enter the file name to write to... ")
    tmp_write = open(str(fileName), "w")
    for line in tmp_read:
        if str(line).isalpha():
            tmp_write.write(str(line).lower())
    print("Successful!")

if __name__ == "__main__":
    lower_case()
030
  • 10,842
  • 12
  • 78
  • 123
delc
  • 1
  • 4
  • 1
    What exactly is your question? Are you aware that you're iterating over the file by line, so if there is a single non-letter character on a line, that line will be skipped entirely? Also, all the calls to `str()` are unnecessary since the parameters already are strings. – Tim Pietzcker Oct 11 '14 at 09:12
  • 3
    To improve your question, provide sample input, expected output, and actual output. – Mark Tolonen Oct 11 '14 at 09:14
  • 1
    You are comparing an entire line, when you should be comparing each character. – Burhan Khalid Oct 11 '14 at 10:28

2 Answers2

0

This checks weather a character isalpha() or isspace() then write in new file.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def lower_case():

    input_name = input("Enter the file name to read from: ")
    output_name = input("Enter the file name to write to... ")

    with open(str(input_name), 'r') as i:
        content = i.readlines()
        with open(str(output_name),'wb') as o:
            for line in content:
                o.write(''.join(c for c in line if c.isalpha() or c.isspace()).lower())

if __name__ == "__main__":
    lower_case()
rynangeles
  • 104
  • 1
  • 3
-1

Code

input_f = input("Enter the file name to read from: ")
output_f = input("Enter the file name to write to... ")

fw = open(output_f, "w")

with open(input_f) as fo:
    for w in fo:
        for c in w: 
            if c.isalpha():
                fw.write(c.lower())
            if c.isspace():
                fw.write('\n')

fo.close()
fw.close()

input.txt

HELLO
12345
WORLD
67890
UTRECHT
030
dafsf434ffewr354tfffff44344fsfsd89087uefwerwe

output.txt

hello

world

utrecht

dafsfffewrtffffffsfsduefwerwe

Sources

  1. How to convert string to lowercase in Python?

  2. http://www.tutorialspoint.com/python/file_readlines.htm

  3. http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

  4. How to read a single character at a time from a file in Python?

  5. How to check if text is "empty" (spaces, tabs, newlines) in Python?

Community
  • 1
  • 1
030
  • 10,842
  • 12
  • 78
  • 123