AttributeError: 'str' object has no attribute 'write' error in last line, need insight

Viewed 875

Problem Prompt: write all file content into new file by skipping line 5 from following file.

Testfile:

line1
line2
line3
line4
line5
line6
line7

newFile:

line1
line2
line3
line4
line6
line7

Code:

testFile = 'C:/Users\Karan\Documents\\test.txt'
newFile = 'C:/Users\Karan\Documents\\newtext.txt'

for num, line in enumerate(testFile, 1):
    if num != 5:
        newFile.write(line)
Errors:

Traceback (most recent call last):
  File "C:/Users/Karan/AppData/Roaming/JetBrains/PyCharm2020.1/scratches/scratch_1.py", line 7, in <module>
    newFile.write(line)
AttributeError: 'str' object has no attribute 'write'

I know it's an issue with the last line, But I've been pounding away at it all day and would really like a fresh set of eyes to look into it.

3 Answers

newFile is the name of the file you wanted to open, not the File object created by actually opening the file with that name.

And indeed the error says "str has no attribute...", because the object you're using is a string.

I believe you did more correct in your code than some answers are giving you credit for -- particularly in your use of enumerate(). It's the file opening, as well as possibly the file name strings, that are at issue here:

testFile_name = r"C:\Users\Karan\Documents\test.txt"
newFile_name = r"C:\Users\Karan\Documents\newtext.txt"

with open(testFile_name) as testFile:
    with open(newFile_name, 'w') as newFile:
        for number, line in enumerate(testFile, 1):
            if number != 5:
                newFile.write(line)

You need to use open() to first open the files before you can read and write them.

with open('C:/Users\Karan\Documents\\test.txt') as testFile:
    File = testFile.readlines()

with open('C:/Users\Karan\Documents\\newtext.txt','w') as newFile:
    File.pop(4) # Remove the fifth line
    newFile.write(''.join(File))

UPDATE:

As stated in the comments by @cdlane, it's not a good practice to write the whole file into memory when unnecessary. Instead, write the file line by line:

with open('C:/Users\Karan\Documents\\test.txt','r') as testFile, open('C:/Users\Karan\Documents\\newtext.txt','w') as newFile:
    for num, line in enumerate(testFile, 1):
        if num != 5:
            newFile.write(line)
Related