A python code read each line in the input file, check if there is no negative number and ignore all space
时间: 2024-05-08 10:16:55 浏览: 104
Assuming the input file has one number per line, here is an example code:
```
with open('input.txt', 'r') as f:
for line in f:
# Remove all spaces
line = line.replace(" ", "")
# Check if line is a negative number
if line.startswith("-"):
print("Error: Negative number found.")
continue
# Convert line to integer and do something with it
num = int(line)
print("The number is:", num)
```
This code uses a `with` statement to automatically close the file once we're done reading from it. We then iterate over each line in the file using a `for` loop.
Inside the loop, we first remove all spaces from the line using the `replace` method. We then check if the line is a negative number by using the `startswith` method to see if it begins with a `-` sign. If it does, we print an error message and use the `continue` statement to skip to the next iteration of the loop.
If the line is not a negative number, we convert it to an integer using the `int` function and store it in the `num` variable. We can then do something with this number, such as printing it out.
阅读全文