还有其他方法可以迭代和读取文件吗?

问题描述 投票:0回答:1

我准备了一个小项目,但遇到了逻辑错误。这个函数在操作.py中 称为 land_available 应该通过读取 data.txt 文件来检查土地是否可用,如果是,则应该运行此函数租用土地。但它没有运行。你能帮帮我吗,我现在陷入了巨大的困境。

我试过:

       |-------------------------------------------------------------------------------------------------------------|
         |                                      The basic information of the company                                   |
         |-------------------------------------------------------------------------------------------------------------|
Type 1 to rent land 
Type 2 to return land 
Type 3 to dislpay land 
Type 4 to exit the system
Enter a value:1
101             Bhaktapur      West           3              70000            Available
102             Kathmandu      South          1              20000            Not Available
103             Dhankuta       North          10             60000            Available
104             Dhangadi       East           7              90000             Available
Invalid data for key 105.
enter the required kitta number101
Sorry, land is not available
Do you want to continue renting (yes/no):    

我期待

rent_land
功能发挥作用

这是代码

main.py:

from read import *
from operations import *

def main():
    print("\t |-------------------------------------------------------------------------------------------------------------|")
    print("\t |                                      The basic information of the company                                   |")
    print("\t |-------------------------------------------------------------------------------------------------------------|")

    # Called read_data() to get the data
    a = read_data()
    keepRunning = True
    
    while keepRunning == True:
        
        print("Type 1 to rent land ")
        print("Type 2 to return land ")
        print("Type 3 to dislpay land ")
        print("Type 4 to exit the system ")
        userOption = int(input("Enter a value:"))
        if userOption == 1:
            

            #to make sure user wants to continue
            renting = True
            while renting == True:                
                #displayed land information ask kitta no, validate it no,
                displayer(a)  # Pass the values of the dictionary to the display function

                #taken inputs from the user to rent the land
                kitta_number = int(input("enter the required kitta number"))
                if exist(kitta_number) and land_available(kitta_number):

                    Customer_name = input("Enter your name")
                    duration = int(input("Enter the duration of renting"))                    

                    #called the function rent_land with the inputs as arguments passed 
                    rent_land(kitta_number,Customer_name,duration)
                
                userInput = input("Do you want to continue renting (yes/no): ").lower()
                if userInput != "yes":
                    renting = False

        elif userOption == 2:
            #return land similar to rent
            print("Call method to return land ")
        elif userOption == 3:
            # Call read_data() to get the data1
               
                displayer(a)  # Pass the values of the dictionary to the display function


        elif userOption == 4:
            print("You are exiting the system")
            keepRunning = False
        else:
            print("Enter valid input only 1 or 2 or 3")


main()

操作.py:

from read import read_data
from read import read_invoice
from write import *

#function to rent a land 
def rent_land(kitta_number, Customer_name, duration):
    if exist(kitta_number) and land_available(kitta_number):
        rent(kitta_number,Customer_name,duration)
        print("Rental successfull")
        generate_invoice(kitta_number, Customer_name, duration)

    else:
        print("Sorry, the land's not available")

#function to check if available

def exist(kitta_number):
    
    land_data = read_data()
    
    if kitta_number in land_data:
        return True
    else:
        print("The land with kitta number " + str(kitta_number) +" doesn't exist")


def land_available(kitta_number):
    land_data = read_data()  
    for data in land_data.values():
        
        availability = data[-1]  
        if availability == "Available":
            return True
        else:
            print("Sorry, land is not available")
            return False
    print("The selected kitta number is not found.")
    return False

def rent(kitta_number,Customer_name,duration): 
    land_data = read_data()

    if kitta_number in land_data:
        land_data[kitta_number][-1] = "Not Available"
        write_data(land_data)
    else:
        print("The land with" + kitta_number +" doesn't exist")

def generate_invoice(kitta_number, Customer_name, duration):
    land_data = read_data()  
    for data in land_data.values():
        
        cost = data[-2]
        place = data[2]
        write_invoice(kitta_number,place, Customer_name, duration,cost)
        
        read_invoice()

阅读.py:

def read_data():
    with open("data.txt", 'r') as file:
        Kitta_dictionary = {}
        kitta_no = 101
        for line in file:
            line = line.strip()  # Remove leading/trailing whitespaces including '\n'
            Kitta_dictionary[kitta_no] = line.split(',')
            kitta_no += 1
        return Kitta_dictionary  # Return the dictionary instead of printing it

# Display function
def displayer(data):
    for key, row in data.items():
        if not row or len(row) < 5:  # Check if row is empty or has fewer than 6 elements
            print(f"Invalid data for key {key}.")
            continue
        print(row[0] + ' '*(15-len(row[0])) +
              row[1] + ' '*(15-len(row[1])) +
              row[2] + ' '*(15-len(row[2])) +
              row[3] + ' '*(15-len(row[3])) +
              row[4] + ' '*(17-len(row[4])) +
              row[5])

def read_invoice():
    # Read the contents of the invoice file
    with open("invoice.txt", "r") as file:
        return file.read()

写.py:

from datetime import datetime

def write_data(data):
    with open("data.txt", 'w') as file:
        for kitta, data in data.items():
            line = ','.join(data)  # Convert the data tuple to a string
            file.write(line + '\n')

def write_invoice(kitta_number, place, Customer_name, duration, cost):
    # Get the current date and time
    current_datetime = datetime.now()

    # Format the datetime object as a string
    formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

    with open("invoice.txt", "w") as file2:
        file2.write("-------------------------------------------   Invoice  -----------------------------------------------------\n")
        file2.write("                                  " + str(formatted_datetime) + "                                                    \n")
        file2.write("LAND: " + str(kitta_number) + "                   Location: " + place + "\n")
        file2.write("         Duration of rent: " + str(duration) + "     Cost:" + str(cost) + "\n")
        file2.write("                          Rented By:" + Customer_name + "\n")
        file2.write("------------------------------------------------------------------------------------------------------------\n")

数据.txt:

101, Bhaktapur, West, 3, 70000, Available
102, Kathmandu, South, 1, 20000, Not Available
103, Dhankuta, North, 10, 60000, Available
104, Dhangadi, East, 7, 90000,  Available
python
1个回答
0
投票

您的

land_available
函数中的逻辑存在问题。我们来看看:

def land_available(kitta_number):
land_data = read_data()  
for data in land_data.values():
    
    availability = data[-1]  
    if availability == "Available":
        return True
    else:
        print("Sorry, land is not available")
        return False
print("The selected kitta number is not found.")
return False

问题出在循环上。如果数据文件中的第一个土地条目不可用,它将立即返回

False
,即使具有指定
kitta_number
的土地稍后可能在文件中可用。

要解决此问题,只有在迭代了所有土地条目但未找到指定的

False
时,才应返回
kitta_number
。这是该函数的更正版本:

def land_available(kitta_number):
land_data = read_data()
for data in land_data.values():
    if data[0] == str(kitta_number):  # Check if the kitta number matches
        availability = data[-1]  
        if availability == "Available":
            return True
        else:
            print("Sorry, land is not available")
            return False
print("The selected kitta number is not found.")
return False

在此更正的版本中,它会迭代所有土地条目,直到找到与指定的

kitta_number
匹配的内容。如果找到匹配项,则会检查可用性。如果没有找到任何匹配项,则会打印消息 “未找到所选的 kitta 号码” 并在循环后返回
False
。这确保它在得出土地不可用的结论之前检查所有土地条目。

© www.soinside.com 2019 - 2024. All rights reserved.