0

我正在尝试设置一个脚本来重写接口文件,最终它将IP地址更改为静态,但是当我运行它时,我收到一个错误,显示为'new_location_interfaces.truncate()'的行,它说那个'str'对象没有属性截断。

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()

我对 python 很陌生,我的代码可能很糟糕,但任何帮助都将不胜感激。

4

1 回答 1

3

new_location_interfaces不是文件对象。它是一个字符串,raw_input()调用的结果:

new_location_interfaces = raw_input()

下一行,open()调用,没有分配给任何东西:

open(new_location_interfaces, 'w')

也许你想截断那个对象?

例如:

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()

但是,打开文件进行写入(模式设置为w已经截断了文件,您的.truncate()调用完全是多余的。

于 2013-09-21T19:13:07.380 回答