首页 / PYTHON / 用Python读写文件
用Python读写文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了用Python读写文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2151字,纯文字阅读大概需要4分钟。
内容图文
![用Python读写文件](/upload/InfoBanner/zyjiaocheng/696/a0b35c5effff42c8a591d815e717899a.jpg)
我正在编写一个具有两个输入的脚本:
>包含名称列表的文件,
>不同的文件(可以为空或非空)
该脚本的目的是从第一个文件中获取名称,访问某个API并获取每个名称的信息,然后将该信息写入第二个文件.如果第二个文件已经包含信息,则脚本将读取已写文件的最后一行,在第一个文件中找到该条目,然后从该条目开始.但是,在读写第二个文件时遇到了麻烦.
当我将第二个文件类型设置为“ r”,然后在file_two.read()上进行打印时,它将显示第二个文件的内容.当我在下一行进行另一次打印时,它显示文件为空.同样,当我将文件类型设置为“ a”时,即使我可以清楚地看到文本文件中的信息确实存在,两次也都将文件显示为完全空.有人知道发生了什么吗?
这是处理写作的代码段:
def write_to_file(filename, users):
pages = range(0, len(users) - 100, 100)
for page in pages:
user_names = get_users(users[page: page+100])
lines = [format_user(user) for user in user_names]
output_text = '\n'.join(lines)
with filename as output_file:
output_file.write(output_text.encode('utf-8'))
这是调用上述函数的代码段.
file_one = args.file1
file_two = args.file2
users = read_names_automatic(file_one)
write_to_file(file_two, users)
解决方法:
When I set the second file type to “r+” and then do a print on file_two.read(), it shows the contents of the second file. When I do another print on the very next line, it shows the file as empty.
是的,这是预期的行为.文件指针指向file_two.read()末尾的文件末尾,因此任何进一步读取的尝试都会返回一个空字符串.例如,检查以下内容:
with open("test.txt") as f:
print f.readline() # => prints the first line, sets file pointer to second line
print f.read() # => prints everything from the second line on
要将文件指针重置为文件的开头,请执行以下操作:
with open("test.txt") as f:
print f.read() # => prints entire file, sets file pointer to end of file
f.seek(0) # => reset file pointer to beginning of file
print f.read() # => prints entire file
As well, when I set the file type to “a+”, it shows the file as completely empty both times, even though I can clearly see the information in the text file is indeed there.
当您打开(“ test.txt”,“ a”)时,文件指针设置为文件的末尾,因此任何读取尝试都会产生一个空字符串.确实,这就是您可以附加到文件的原因.如果先是file_two.seek(0),然后是file_two.write(),则将书面文本添加到file_two的开头.
内容总结
以上是互联网集市为您收集整理的用Python读写文件全部内容,希望文章能够帮你解决用Python读写文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。