Python 语法截断错误



我正在尝试设置一个重写接口文件的脚本,最终它会将 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 lon
iface lo inet loopback
iface etho inet dhcpn
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很陌生,我的代码可能很糟糕,但任何帮助将不胜感激。

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()调用完全是多余的。

尝试缩进空格,这里由于随机错误而发生的错误也尝试 c 中的 for x:打印 c

相关内容

  • 没有找到相关文章

最新更新