如何解决使用函数读写文件 您的代码问题解释为注释这是代码的外观一种更Python化的方法
我正在尝试创建2个函数。
一个接一个地使用时,输出文件应该是输入文件的精确副本(包括格式)
这是我到目前为止所拥有的。
file_path = ("/myfolder/text.txt","r")
def readfiles(file_path):
with open file_path as f:
for line in f:
return line
lst = list[]
lst = line
lst.append(line)
return lst
read_file(file_path)
lines = lst []
def writefiles(lines,file_path):
with open ("file_path","w") as f:
for line in lst:
f.write(line)
f.write("\n")
使用它进行阅读时,我可以将其用于某种工作
with open("/myfolder/text.txt","r") as f:
for line in f:
print(line,end='')
这是写
with open ("/myfolder/text.txt","w") as f:
for line in f:
f.write(line)
f.write("\n")
但是当我尝试将它们放入函数中时,一切都搞砸了。 我不知道为什么,我知道这是一个简单的问题,但这并不是我想要的。我已经阅读过有关它的文档,但是我没有完全关注它,并且不知所措。我的功能出了什么问题?
我从中得到各种错误
lst = list[]
^
SyntaxError: invalid Syntax
到
lst or list is not callable
我也知道有类似的问题,但是我发现的问题似乎没有定义函数。
解决方法
您的代码问题解释为注释
import React,{ Component } from "react";
import { PanResponder,Dimensions,View,ImageBackground,Image,Text } from "react-native";
import Svg,{ Path,Circle,G } from "react-native-svg";
import ScrollableTabView from 'react-native-scrollable-tab-view';
import TabBar from 'react-native-underline-tabbar';
import { RFPercentage } from "react-native-responsive-fontsize";
import * as Font from "expo-font";
export default class CircleSlider extends Component {
constructor(props) {
super(props);
this.state = {
angle: this.props.value,};
panResponder = PanResponder.create({
onStartShouldSetPanResponder: (e,gs) => true,onStartShouldSetPanResponderCapture: (e,onMoveShouldSetPanResponder: (e,onMoveShouldSetPanResponderCapture: (e,onPanResponderMove: (e,gs) => {
let xOrigin =
this.props.xCenter - (this.props.dialRadius + this.props.btnRadius);
let yOrigin =
this.props.yCenter - (this.props.dialRadius + this.props.btnRadius);
let a = this.cartesianToPolar(gs.moveX - xOrigin,gs.moveY - yOrigin);
if (a <= this.props.min) {
this.setState({ angle: this.props.min });
} else if (a >= this.props.max) {
this.setState({ angle: this.props.max });
} else {
this.setState({ angle: a });
}
},});
}
polarToCartesian(angle) {
let r = this.props.dialRadius;
let hC = this.props.dialRadius + this.props.btnRadius;
let a = ((angle - 90) * Math.PI) / 180.0;
let x = hC + r * Math.cos(a);
let y = hC + r * Math.sin(a);
return { x,y };
}
cartesianToPolar(x,y) {
let hC = this.props.dialRadius + this.props.btnRadius;
if (x === 0) {
return y > hC ? 0 : 180 ;
} else if (y === 0) {
return x > hC ? 90 : 270;
} else {
return (
Math.round((Math.atan((y - hC) / (x - hC)) * 180) / Math.PI) +
(x > hC ? 90 : 270)
);
}
}
render() {
if (!this.state.fontLoaded) { return null; }
let width = (this.props.dialRadius + this.props.btnRadius) * 2;
let bR = this.props.btnRadius;
let dR = this.props.dialRadius;
let startCoord = this.polarToCartesian(0);
let endCoord = this.polarToCartesian(this.state.angle);
return (
<View >
<ImageBackground
source={require("../../assets/SaatBackGround.png")}
resizeMode="contain"
style={{
width: "80%",height: "100%",position: "absolute",marginTop: "15%",alignSelf: "center",}}
imageStyle={{ height: "100%",width: "100%" }}
>
<Image
style={{ height: "55%",width: "50.2%",marginTop:"22%" }}
resizeMode="contain"
source={require("../../assets/ClockCircle.png")}></Image>
</ImageBackground>
<View style={{ justifyContent: "center",marginTop: "32%",marginLeft: "27.5%" }}>
<Svg width={width} height={width}>
<Circle
r={dR}
cx={width / 2}
cy={width / 2}
stroke={this.props.strokeColor}
strokeWidth={this.props.strokeWidth}
fill={this.props.fillColor}
/>
<Path
stroke={this.props.meterColor}
strokeWidth={this.props.dialWidth}
fill="none"
d={`M${startCoord.x} ${startCoord.y} A ${dR} ${dR} 0 ${
this.state.angle > 180 ? 1 : 0
} 1 ${endCoord.x} ${endCoord.y}`}
/>
<G x={endCoord.x - bR} y={endCoord.y - bR}>
<Circle
r={bR}
cx={bR}
cy={bR}
fill={this.props.meterColor}
{...panResponder.panHandlers}
/>
</G>
</Svg>
</View>
</View>
);
}
}
CircleSlider.defaultProps = {
btnRadius: 15,dialRadius: 78,dialWidth: 5,meterColor: "#fff",textColor: "#124F7B",fillColor: "none",strokeColor: "#fff",strokeWidth: 0.1,textSize: 10,value: 0,min: 0,max: 719,xCenter: Dimensions.get("window").width / 2,yCenter: Dimensions.get("window").height / 2,onValueChange: (x) => x,};
这是代码的外观
file_path = ("/myfolder/text.txt","r") # this is a tupple of 2 elements should be file_path = "/myfolder/text.txt"
def readfiles(file_path):
with open file_path as f: # "open" is a function and will probably throw an error if you use it without parenthesis
# use open this way: open(file_path,"r")
for line in f:
return line # it will return the first line and exit the function
lst = list[] # "lst = []" is how you define a list in python. also you want to define it outside the loop
lst = line # you are replacing the list lst with the string in line
lst.append(line) # will throw an error because lst is a string now and doesn't have the append method
return lst
read_file(file_path) # should be lines = read_file(file_path)
lines = lst [] # lines is an empty list
def writefiles(lines,file_path):
with open ("file_path","w") as f:
for line in lst: # this line should have 1 more tabulation
f.write(line) # this line should have 1 more tabulation
f.write("\n") # this line should have 1 more tabulation
一种更Python化的方法
def readfiles(file_path):
lst = []
with open(file_path) as f:
for line in f:
lst.append(line.strip("\n"))
return lst
def writefiles(lines,file_path):
with open(file_path,"w") as f:
for line in lines:
f.write(line + "\n")
file_path = "/myfolder/text.txt"
filepathout = "myfolder/text2.txt"
lines = readfiles(file_path)
writefiles(lines,filepathout)
要点:
# readlines is a built-in function in python
with open(file_path) as f:
lines = f.readlines()
# stripping line returns
lines = [line.strip("\n") for line in lines]
# join will convert the list to a string by adding a \n between the list elements
with open(filepathout,"w") as f:
f.write("\n".join(lines))
定义变量:
- the function stops after reaching the return statement
- be careful where you define your variable.
i.e "lst" in a for loop will get redefined after each iteration
,
这里有一些学习要点会有所帮助。
在阅读功能中,您有点接近。但是,不能将return
语句放入循环中。该功能首次在任何地方出现时,它就会结束。另外,如果要创建一个容器来保存已读取的内容列表,则需要在开始之前 进行设置。最后,不要命名list
。它是一个关键字。如果要创建新的列表项,只需执行以下操作:results = list()
或results = []
因此,在伪代码中,您应该:
Make a list to hold results
Open the file as you are now
Make a loop to loop through lines
append to the results list
return the results (outside the loop)
您的writefiles
非常接近。您应该遍历lines
变量,该变量是函数的参数。现在,您引用的不是函数的参数lst
。
祝你好运!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。