Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么打印功能不能在open_中使用?_Python_Python 3.x - Fatal编程技术网

Python 为什么打印功能不能在open_中使用?

Python 为什么打印功能不能在open_中使用?,python,python-3.x,Python,Python 3.x,我正在启动一个模块,打开一个文件,读取它,做一些事情,然后附加到它。但是,我试图先查看文件中的内容。以下是该计划的开始: def addSkill(company): with open("companies.txt", "a+") as companies: for line in companies: print('ok') print(line.rstrip('\n')) companies.write

我正在启动一个模块,打开一个文件,读取它,做一些事情,然后附加到它。但是,我试图先查看文件中的内容。以下是该计划的开始:

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()

两个打印功能都不工作。文件中有文本。并根据请求附加到它。有什么建议吗?

只需使用
'r+'
打开,然后将所需的所有内容保存在内存中,然后它将在最后自动写入。因为您的文件描述符将位于末尾

'a'
中打开文件会自动将文件描述符放在末尾,因此,您无法看到之前写的内容

e、 g

奖金:您的
close()
方法在使用
时是无用的,python会帮您做到这一点

在任何情况下,当您不确定某个函数的选项时,请

  • 'r'
    打开阅读(默认)
  • 'w'
    打开进行写入,首先截断文件
  • 'x'
    以独占方式打开创建,如果文件已存在,则失败
  • 'a'
    打开进行写入,如果文件存在,则追加到文件末尾
  • 'b'
    二进制模式
  • 't'
    文本模式(默认)
  • “+”
    打开磁盘文件进行更新(读写)
  • 'U'
    通用换行符模式(已弃用)

您使用
a
,因此光标位于文件的末尾。@Willem Van Onsem您应该将其列为答案,这样您就可以获得学分。也许我错了,但我认为我读的是a+,而读取光标放在开头?有没有一种有效的方法可以在不执行单独的w和a方法的情况下读取和追加数据,这会让您回到起点。
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'.