简体   繁体   English

为什么打印功能在open_with中不起作用?

[英]Why is the print function not working in open_with?

I am starting a module that opens a file, reads it, does some stuff, and then appends to it. 我正在启动一个模块,该模块打开文件,读取文件,执行一些操作,然后将其追加。 However, I am trying to see what is in the file first. 但是,我试图首先查看文件中的内容。 Here is the start of the program: 这是程序的开始:

def addSkill(company):
    with open("companies.txt", "a+") as companies:
        for line in companies:
            print('ok')
            print(line.rstrip('\n'))
        companies.write(company + '\r\n')

    companies.close()

Neither of the print functions are working. 两种打印功能均不起作用。 There is text in the document. 文件中有文字。 And it appends to it as requested. 并按要求附加到它。 Any suggestions? 有什么建议么?

Just open using 'r+' then save in memories everything that you need, then it will automatically writing at the end. 只需使用'r+'打开,然后将所需的所有内容保存在内存中,然后它将在最后自动写入。 because your file descriptor will be at the end. 因为您的文件描述符将在末尾。

Opening files in 'a' automatically put your file descriptor at the end, therefore, your can't see what was written before that. 'a'打开文件'a'自动将文件描述符放在末尾,因此,您看不到之前的内容。

eg 例如

def addSkill(company):
    with open('companies.txt', 'r+') as fd:
        list_of_companies = fd.readlines()
        fd.write(company + '\n')

list_of_companies.append(company) # adding the last company to the full list.
print('\n'.join(list_of_companies)) # print each company with a '\n'.

Bonus : your close() method is useless using with , python will do that for you. 奖励 :您的close()方法with使用是无用的,python会帮您做到这一点。

In any cases, when you are unsure about the option of a function, please RTFM : open() 无论如何,当您不确定某个函数的选项时,请RTFMopen()

  • 'r' open for reading (default) 'r'打开以供阅读(默认)
  • 'w' open for writing, truncating the file first 'w'打开进行写入,首先截断文件
  • 'x' open for exclusive creation, failing if the file already exists 打开'x'以进行独占创建,如果文件已存在则失败
  • 'a' open for writing, appending to the end of the file if it exists 可写的'a' ,追加到文件末尾(如果存在)
  • 'b' binary mode 'b'二进制模式
  • 't' text mode (default) 't'文本模式(默认)
  • '+' open a disk file for updating (reading and writing) '+'打开磁盘文件以进行更新(读取和写入)
  • 'U' universal newlines mode (deprecated) 'U'通用换行模式(不建议使用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM