python - 在 python 中读取、写入、追加和删除文件

标签 python ubuntu

这是我的代码,我需要你的帮助。

我的程序应该接受数据输入、创建新文本文件、读取和写入文本文件、将文本追加到现有文本文件中、截断和删除文件。 现在我的程序遇到的问题是,应该附加文本、截断文本文件的内容和删除文本文件的代码部分不起作用,并且程序在运行时不会返回任何错误。

import os
from sys import argv

filename = argv

def menu():
    holder = input("enter 1 to create new file or 2 to use existing ones\n")
    if holder == 1:
        dam = raw_input("Enter name of new text file:\n")+'.txt'
        textfile = open(dam, 'w+')
        happ = raw_input("\nPlease enter record into your new file\n\n")
        textfile.write(happ)
        textfile.close()
        print "*******************"
        print "*******************\n"

        print "To view the content of your new file, enter 'yes' otherwise enter 'no' to exit"

        gett = raw_input()

        if gett == 'yes':

            print "*******************"
            print "\nyour inputted record is>>>\n"
            display = open(dam)
            print(display.read())
            print'\n'
            menu()
        elif gett == 'no':
            print ("\nOk, see you later. Have a nice day!")
            print'\n'
            menu()
        else:
            print "\nyou have entered a wrong input"
            print '\n'
            menu()
   elif holder == 2:
       filename = raw_input("Enter name of file:\n")+'.txt'
       entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
       if entry == 7:
           print ("Displayed below is the content of your file, continue to append more text at the bottom of the file.(text is limited to 3 lines)\n")
           textfiles = open(filename, 'a+')
           print (textfiles.read())
           line1 = raw_input( )
           line2 = raw_input( )
           line3 = raw_input( )
           print "\nSaving..."
           textfiles.write(line1)
           textfiles.write('\n')
           textfiles.write(line2)
           textfiles.write('\n')
           textfiles.write(line3)
           textfiles.write('\n')
           print "\nSaved!"
           textfiles.close()
       elif entry == 8:
           textfiles = open(filename, 'w')
           print "Truncating the file..."
           textfiles.truncate()
           print "Done, truncated."
           textfiles.close()
           right = raw_input("Do you want to write into this file? Y/N : ")
           if right == 'Y':
               textfiles = open(filename, 'a+')
               print "text is limited to 3 lines"
               line1 = raw_input('\n')
               line2 = raw_input()
               line3 = raw_input()
               print "\nSaving..."
               textfiles.write(line1)
               textfiles.write('\n')
               textfiles.write(line2)
               textfiles.write('\n')
               textfiles.write(line3)
               textfiles.write('\n')
               print "\nSaved!"
               textfiles.close()
           else:
               print "Ok have a nice day"
       elif entry == 9:
            print "Deleting the file..."
            try:
                os.remove(filename)
            except OSError, e:  #if failed, report it back to the user
                print ("Error: %s - %s." % (e.filename, e.strerror))
                print "Done, deleted."
       else:
           print "Error! wrong entry"
           print '\n'
           menu()
    else:
        print "\nyou have entered a wrong input"
        print '\n'
        menu()
menu()

这是它给出的输出

输入 1 创建新文件或输入 2 使用现有文件

2

输入文件名:

测试

按 7 将文本追加到此文件中,按 8 截断此文件的内容,或按 9 删除此文件:8

错误!错误输入

输入 1 创建新文件或输入 2 使用现有文件

关于如何完成这项工作的任何帮助?

最佳答案

您正在为变量 entry 使用函数 raw_input()

entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")

引用python2(https://docs.python.org/2/library/functions.html#raw_input)的文档,函数raw_input返回一个String

之后,您将根据 integer 值测试您的变量 entry。由于 String 永远不会等于 int,因此测试将无法进行。并且您的代码落在最后一个条件 block 中,即“错误输入”

要解决此问题,您应该像在代码开头那样使用 input 函数 (https://docs.python.org/2/library/functions.html#input):

entry = input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")

或将 entry 转换为 int

entry = int(raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : "))

关于python - 在 python 中读取、写入、追加和删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36914326/

相关文章:

python - 如何向 string.punctuation 添加更多标点符号

linux - Chef 版本不匹配

ubuntu - pam.conf 为空

python - Keras 函数式 API 和 TensorFlow Hub

python - 提高元素 block 之间差异的性能

python - Django 项目模板加载器设置

python - 超大表的数据库解决方案

ubuntu - Mono ServiceStack 过早关闭 tcp 连接

php - 如何使用 Zend_Mail、sendmail 和 localhost 发送电子邮件?

mysql - 在自己的用户上运行 phpMyAdmin