怪异的字符和属性的不足。 Python

Weird characters and deficiency of the attribute. Python

我创建了一个函数,但卡住了。

函数含义:

  1. 用户在文件中键入号码和自己的姓名。

  2. 程序在文件末尾写入名称 'number' 次。

  3. 并且只打印出文件的内容。

有什么问题?

  1. 程序读取文件时有奇怪的字符,下面有一个大space。

像这样:਍圀逼逼逼逼逼抢逼攀㬀 。ⴀ 逼闪闪闪逼逼ഀഀ(然后在Powershell中有一个巨大的space 10-15行)

  1. 错误:'str' 对象没有属性 'close'。

    def filemania():
    
        print "Great! This way is called \"Filemania\""
    
        file_name = raw_input("Type in any text file> ")
        enter_1 = int(raw_input("Enter an integer> "))
        enter_2 = raw_input("Enter your name> ")
    
        print "Now your name will apear in the file %d times at the end" % enter_1
    
        open_file = open(file_name, 'a+')
        listok = []
    
        while len(listok) < enter_1:
            open_file.write(enter_2 + " ")
            listok.append(enter_2) 
    
        print "Contains of the file:"
        read_file = open_file.read()
        print read_file
        file_name.close()
    
    filemania()
    

我认为问题出在某个地方:

open_file = 打开(file_name, 'a+')

有人知道如何解决这些问题吗?

对于第二个错误,您试图关闭 file_name,这是原始输入字符串。你的意思是关闭 open_file

试试看,然后反馈。

首先你设置 file_name = raw_input("Type in any text file> ") 所以你试图用 file_name.close():

关闭一个字符串

当您写入 open_file 时,您将指针移动到文件末尾,因为您正在追加,所以 read_file = open_file.read() 不会按照您的想法进行。

您将需要再次定位到文件的开头以打印内容,open_file.seek(0)

def filemania():
    print "Great! This way is called \"Filemania\""
    file_name = raw_input("Type in any text file> ")
    enter_1 = int(raw_input("Enter an integer> "))
    enter_2 = raw_input("Enter your name> ")

    print "Now your name will apear in the file %d times at the end" % enter_1

    # with automatically closes your files
    with open(file_name, 'a+') as open_file:
        listok = []
        # use range      
        for _ in range(enter_1):
            open_file.write(enter_2 + " ")
            listok.append(enter_2)
        print "Contains of the file:"
        # move pointer to start of the file again
        open_file.seek(0) 
        read_file = open_file.read()
        print read_file

filemania()