Search code examples
pythonsyntaxtruncate

Python Syntax Truncate Error


I'm trying to set up a script that re-writes the interfaces file and eventually it will change the ip address to static, but when I run it I get an error the line that reads ' new_location_interfaces.truncate()' and it says that 'str' object has no attribute truncate.

from sys import argv
from os.path import exists
import os

script_name = argv

print "You are currently running %s" % script_name
print "Version: 0.1"
print """Desciption: This script will change the IP address of the
Raspberry Pi from dynamic to static.
"""
print "If you don\'t want to continue, hit CTRL-C (^C)."
print "If you do want that, hit RETURN"

raw_input("?")

# Main code block

text_to_copy = """
auto lo\n
iface lo inet loopback
iface etho inet dhcp\n
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
"""

if exists("/etc/network/interfaces"):
    print "\nFile exists."
    interfaces_file = open("/etc/network/interfaces", 'w')
    print "Truncating/erasing contents . ."
    interfaces_file.truncate()
    print "Writing contents . ."
    interfaces_file.write(text_to_copy)
    interfaces_file.close()
else:
    print "\nCould not find the \'interfaces\' file."
    print "Please specify the location:",
    new_location_interfaces = raw_input()
    open(new_location_interfaces, 'w')
    print "Truncating/erasing contents . ."
    new_location_interfaces.truncate()
    print "Writing contents . ."
    new_location_interfaces.write(text_to_copy)
    new_location_interfaces.close()

I am very new to python and my code is probably terrible but any help would be appreciated.


Solution

  • new_location_interfaces is not a file object. It is a string, the result of the raw_input() call:

    new_location_interfaces = raw_input()
    

    The next line, the open() call, is not assigned to anything:

    open(new_location_interfaces, 'w')
    

    Perhaps you wanted to truncate that object?

    For example:

    new_location_interfaces = raw_input()
    fh = open(new_location_interfaces, 'w')
    print "Truncating/erasing contents . ."
    fh.truncate()
    print "Writing contents . ."
    fh.write(text_to_copy)
    fh.close()
    

    However, opening a file for writing (mode set to w) already truncates the file, your .truncate() calls are entirely redundant.