我正在尝试设置一个重写interfaces文件的脚本,最终它会将ip地址更改为static,但是当我运行它时,我得到一个错误,该行显示为'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的新手,我的代码可能很糟糕,但任何帮助都会受到赞赏。
答案 0 :(得分: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()
调用完全是多余的。