【问题标题】:writing integer values to a file using out.write()使用 out.write() 将整数值写入文件
【发布时间】:2012-06-22 17:08:18
【问题描述】:

我正在生成一些数字(比如说,num)并使用outf.write(num).将数字写入输出文件
但是编译器抛出错误:

"outf.write(num)  
TypeError: argument 1 must be string or read-only character buffer, not int".  

我该如何解决这个问题?

【问题讨论】:

  • 学习阅读错误信息! "参数必须是字符串,而不是 int"
  • 你会发布outf的声明吗?
  • @octopusgrabbus outf = open('outdata.txt', 'w') 从上下文猜测(当然文件名是虚构的:)

标签: python


【解决方案1】:

write() 只接受一个单个字符串 参数,所以你可以这样做:

outf.write(str(num))

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

另请注意,write 不会在您的输出中附加换行符,因此如果您需要它,您必须自己提供。

旁白

使用字符串格式可以让你更好地控制你的输出,例如你可以写(这两个是等价的):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

获取三个空格,整数值前导零,后跟换行符:

007
012

format() 会存在很长时间,所以值得学习/了解。

【讨论】:

  • 别担心,我弄糊涂了。是% 的用法需要一个元组用于多个参数,而不是format()
  • 您介意澄清一下您所说的“现代”是什么意思吗? (如果您澄清/更改答案,我将删除此评论,以免 cmets 变得混乱)
  • @MechtEngineer 简单地说,使用 format 函数是现在在 Python 中格式化文本而不是类似 printf 格式的更首选方式(我同时使用这两种方法,可能 printf 稍微多一些,因为我在 Java、C 中使用它等)。 HTH
【解决方案2】:
f = open ('file1.txt','a') ##you can also write here 'w' for create or writing into file
while True :
    no = int(input("enter a number (0 for exit)"))
    if no == 0 :
        print("you entered zero(0) ....... \nnow you are exit  !!!!!!!!!!!")
        break
    else :
        f.write(str(no)+"\n")

f.close()
   
f1 = open ('Ass1.txt','r')

print("\n content of file :: \n",f1.read())

f1.close()
   

【讨论】:

    【解决方案3】:

    您也可以使用 f-string 格式将整数写入文件

    为了追加使用下面的代码,写一次用'w'替换'a'。

    for i in s_list:
        with open('path_to_file','a') as file:
            file.write(f'{i}\n')
    
    file.close()
    

    【讨论】:

      【解决方案4】:
      i = Your_int_value
      

      例如这样写字节值:

      the_file.write(i.to_bytes(2,"little"))
      

      取决于您的 int 值大小和您喜欢的位顺序

      【讨论】:

      • to_bytes(...) 方法“3.2 版中的新功能。”
      【解决方案5】:

      这些都应该有效

      outf.write("%s" % num)
      
      outf.write(str(num))
      
      print >> outf, num
      

      【讨论】:

      • 其中两个已弃用。
      • @BlaXpirit 一年半,因为 % 格式将在这里长期存在
      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      相关资源
      最近更新 更多